Vs code как создать проект php
Перейти к содержимому

Vs code как создать проект php

  • автор:

How To Install VSCode For PHP On Windows

It provides steps required to install Visual Studio Code or VSCode for PHP development on Windows and getting started with PHP development using the Hello World project.

Visual Studio Code or VSCode is a cross-platform, lightweight editor and became popular in a very short span. It provides support for several programming languages. It also supports plugin development and there are several community-driven plugins available for it.

In this tutorial, we will discuss how to install and prepare Visual Studio Code or VSCode for PHP development on Windows. It provides several features for PHP development including IntelliSense, Syntax Highlighting, Bracket Matching, Snippets, Linting, etc.

It assumes that PHP is already installed on the system. You may also be interested in How To Install WampServer on Windows and How To Install PHP 7 On Windows

Step 1 — Download Visual Studio Code

We can download Visual Studio from the official download page. It provides options for Windows as shown in Fig 1.

Click on the 64-bit installer option as highlighted in Fig 1. All the new systems support 64-bit. Choose your option according to system configuration. The version 1.37.1 gets downloaded while writing this tutorial.

Step 2 — Install Visual Studio Code

In this step, we will install the Visual Studio Code downloaded by us in the previous step. Double click the installer to execute it. It will ask to accept the License Agreement as shown in Fig 2.

Accept the agreement and click on the Next Button. It asks to choose the installation directory as shown in Fig 3.

Choose your preferred location and click on the Next Button. The installer will ask to configure Start Menu as shown in Fig 4.

Now click on the Next Button to continue with the installation. The next screen provides additional configuration options as shown in Fig 5.

Click on the Next Button after choosing appropriate options. The next screen shows the configurations selected by us in the previous screens.

Click on the Install Button to start the installation. The installer will show installation progress and success as shown in Fig 7 and Fig 8 respectively.

This is how we can install Visual Studio Code. After completing the installation, the installer will launch Visual Studio Code and shows the Welcome Screen as shown in Fig 9.

The Customize Section on the right-hand side shows that support for JavaScript is installed by default and it shows options to install support for other languages and tools.

Step 3 — Marketplace

You can see all the available plugins on the Marketplace dedicated for Visual Studio Code. Type php in the search box and click on the Search Button. The results should be similar to one as shown in Fig 10.

We can also browse the available extensions within the IDE by clicking on View -> Extensions or press Ctrl + Shift + x. Enter php on the Search Box and hit Enter Key. It will show the same extensions list within the IDE as we saw on the Marketplace Page as shown in Fig 11.

Step 4 — Install Extensions

We will install the most important extensions as part of this tutorial. Also, make sure that you are using the most recent version of PHP. Your system should have at least PHP 7.2 to use the new features available in PHP 7.

PHP IntelliSense and PHP Debug are the most important extensions that every PHP developer must install for Visual Studio Code. The other extensions can be installed based on the requirements. Install both the extensions as shown in Fig 12 and Fig 13.

Step 5 — Getting started with PHP — Hello World

In this section, we will create our Hello World project i.e. HelloPHP project and write and execute the first script using Visual Studio Code.

Click on File -> Open Folder or press Cntrl + K and Cntrl + O to open the File Chooser to select the project folder. It will open the selected folder as highlighted in Fig 14.

Now click on the New File Icon as highlighted in Fig 15.

Enter the file name as index.php and hit the Enter Key. It will create the PHP file as shown in Fig 16.

Update the file and write the first program to print Hello PHP as shown in Fig 17.

Now right-click the file and choose the option Open In Terminal. It will open the terminal within the editor as shown in Fig 18.

Notes: You can also use the Code Runner extension to execute the code.

We can execute the PHP file on the terminal as we do on command prompt by giving the PHP command as highlighted in Fig 19. It also shows the output on the terminal.

Other option to execute the program is to install the Code Runner Extension as shown below.

Now execute the program and view the output as shown in Fig 21 and 22.

This is how we can install Visual Studio Code for PHP development. We have also written our first hello world program and executed it within the editor using the terminal.

3) Install a XAMPP Package

Kevin Rodríguez

2) (Optional) If you already have IIS or Skype or any Java app that uses the :80 port you might want to change the apache port, but i recommend you to change your app port (you can google how to change it for skype for example). To change the default apache port, follow this steps:

  • Go to the httpd.conf file for Apache
  • Find the Listen line and change the Listen port to your desired port. EX: Listen 80
  • Listen 8066 (Example)
  • Save and restart the server

3) Go to the <ROOT>xampp\htdocs folder and replace it’s contents with your php solution.

4) Open the development folder with Visual Studio Code

In Visual Studio Code, go to File->Open Folder and open <ROOT>xampp\htdocs (Where you did put your PHP Files).

5) Install and configure XDebug

There are two ways of installing the right XDebug version for your development machine:

If you are doing PHP development the most likely is that you already know the phpinfo(); global function.
If not, then create the following file on your htdocs folder:

And place it on your development folder, then open it with your browser, it should like something like this.

Then, copy and paste the page on the XDebug big wizard text field.

This should give you the binary link to install and how to install it, download it and install it.

How To Set Up Visual Studio Code (VS Code) for PHP Development

How To Set Up Visual Studio Code (VS Code) for PHP Development

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems.

With a large collection of extensions for many programming languages, VS Code can be customized to serve a wide variety of development needs. In this guide, you’ll learn how to set up Visual Studio Code for working on PHP projects.

Prerequisites

To follow this guide, you’ll need to download and install the appropriate version of Visual Studio Code for your operating system.

The instructions in this guide were validated on an Ubuntu 20.04 desktop computer, but they should work seamlessly in all operating systems that are supported by VS Code. Please note, though, that keyboard shortcut keys may need to be slightly modified for compatibility with MacOS systems.

Step 1 — Installing VS Code PHP Extensions for Extra Support

Right after installation, VS Code already recognizes PHP code and helps with syntax highlighting, basic debugging, and code indentation. These features are suitable for quick edits or when working with individual PHP scripts. Working in larger projects, though, can become difficult without more context around the code and how each file interacts and integrates within the larger project.

There are a number of VS Code extensions that can help speed up your productivity when working on PHP projects. In this guide, we’ll install and set up PHP Intelephense, a popular PHP extension for VS Code that provides several advanced features such as improved code completion, better navigation between components, rich information tooltips on mouse hover, code auto formatting, and real time error reporting based on static code analysis.

Open the extensions tab by clicking on the last icon on the left menu bar, or by pressing CTRL + SHIFT + X . This will bring up a sidebar menu with a search box and a list of popular or recommended extensions. Type “php” or “intelephense” to locate the PHP Intelephense extension. Click on the Install button to install and enable the extension.

Once installation is complete, Intelephense’s official documentation recommends that you disable the built-in PHP Language Features extension that comes with VS Code.

To disable this extension, type @builtin php in the Extensions search box to locate the built-in PHP extensions. Then click on the settings icon for the PHP Language Features extension, and click the Disable option in the drop-down menu.

If you have any files open in VS Code, you’ll need to reload the editor to apply the changes.

You can install other extensions by following the same process described for the PHP Intelephense extension, but be aware that some extensions will require additional software to be installed on your system. Check the extension documentation to make sure you have requirements set appropriately.

Step 2 — Importing or Creating a New PHP Project

To import an existing PHP project into VS Code, click on the first icon on the left menu bar or type CTRL + SHIFT + E to access the file explorer. Click the Open Folder button and select your project’s directory. In case you are creating a new project, you can create a new folder and select that as your project directory.

The explorer window will now show the project’s directory tree, giving you quick access to files and directories on your project.

Step 3 — Customizing Theme and Editor Font (Optional)

Although not necessary, it is often a good idea to customize the appearance of your editor to make it more comfortable to use in the longer term. As a developer you may spend several hours every day looking at an IDE such as VS Code, and for that reason it’s important to make sure the editor font has an appropriate size, and the contrast is enough for good readability without tiring your eyes too quickly.

You may want to experiment with different themes and fonts in order to find a custom setup that works well for you.

Changing VS Code Theme

VS Code comes with a few different themes that allow you to change the colors used in the editor interface and in the code highlighting. Both dark and light styles are included by default.

Go to File -> Preferences -> Color Theme or type CTRL + K + T to select a different theme for VS Code.

You can also install theme extensions to further customize VS Code’s appearance. If you search for theme within the extensions tab ( CTRL + SHIFT + X ), you’ll find several theme extensions in different styles and colors, including color schemes ported from other popular editors and platforms.

Adjusting the Font

Although the default VS Code font settings will be good enough for many users, you may want to adjust the size and the type of the editor font for increased readability.

If you would like to modify the font size or change to another type, you can go to File -> Preferences -> Settings, then choose Text Editor on the left menu. Then, click on Font in the submenu that opens up. That section contains font family and size settings which you can tweak as preferred.

The changes are immediately saved and applied to all current open files.

Conclusion

Visual Studio Code is a lightweight yet powerful code editor that can be customized to suit the needs of most developers. In this guide, you learned how to install and configure the PHP Intelephense extension for extra support while working on PHP projects, how to import and create new projects within VS Code, and how to customize the editor appearance for a more comfortable coding experience.

For more tutorials on Visual Studio Code, check our VS Code tag page. If you’d like to learn more about PHP development, you can refer to our How To Code in PHP series for an introduction to the language, and our PHP tag page for more PHP tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Настройка Visual Studio Code для разработки PHP

Visual Studio Code (или просто VS Code) – бесплатный редактор исходного кода или интегрированная среда разработки (IDE), доступная для всех основных операционных систем.

Благодаря большому набору расширений VS Code можно легко настроить для удовлетворения самых разнообразных потребностей разработки. В этом руководстве вы узнаете, как настроить Visual Studio Code для работы над проектами PHP.

Требования

Чтобы следовать этому руководству, вам необходимо загрузить и установить соответствующую версию Visual Studio Code для вашей операционной системы.

Инструкции в этом руководстве были проверены на настольном компьютере Ubuntu 20.04, но они должны без проблем работать и в других операционных системах, поддерживаемых VS Code. Однако обратите внимание, что в системах MacOS сочетания клавиш могут немного отличаться.

1: Установка PHP-расширений VS Code

VS Code распознает PHP-код и помогает с подсветкой синтаксиса, базовой отладкой и отступами кода сразу же после установки. Этого вполне достаточно для быстрого редактирования или для работы с отдельными сценариями PHP. Однако более крупные проекты сложно обслуживать без дополнительного контекста вокруг кода и без наглядного понимания того, что делает каждый файл и как он интегрируется в проект.

Существует ряд расширений VS Code, которые помогут повысить вашу продуктивность при работе над проектами PHP. В этом руководстве мы установим и настроим PHP Intelephense, популярное расширение PHP для VS Code, которое предоставляет несколько дополнительных функций: улучшенное автозаполнение кода, навигацию между компонентами, всплывающие подсказки с полезной информацией при наведении курсора мыши, автоматическое форматирование кода и создание отчетов об ошибках в реальном времени на основе статического анализа кода.

Откройте вкладку расширений, нажав на последний значок в левой строке меню или клавиши CTRL+SHIFT+X. Это вызовет меню боковой панели с полем поиска и списком популярных или рекомендуемых расширений. Введите «php» или «intelephense», чтобы найти нужное нам расширение PHP Intelephense. Затем нажмите кнопку Install, чтобы установить и включить расширение.

Официальная документация Intelephense рекомендует после завершения установки отключить встроенное расширение PHP Language Features, которое поставляется с VS Code.

Чтобы сделать это, введите @builtin php в поле поиска расширений. Когда вы найдете его, нажмите на значок настроек для расширения PHP Language Features и выберите параметр Disable в выпадающем меню.

Если в VS Code у вас есть открытые файлы, вам необходимо перезагрузить редактор, чтобы изменения вступили в силу.

Вы можете установить другие расширения, следуя описанному выше процессу, но имейте в виду, что некоторые расширения потребуют установки дополнительного программного обеспечения в вашей системе. Проверьте документацию по интересующему вас расширению, чтобы убедиться, что у вас установлены соответствующие зависимости.

2: Импорт или создание нового проекта PHP

Чтобы импортировать существующий проект PHP в VS Code, нажмите на первый значок в левой строке меню или клавиши CTRL+SHIFT+E – так вы сможете получить доступ к проводнику файлов. Нажмите кнопку Open Folder и выберите каталог своего проекта. Если вы создаете новый проект, вы можете создать новую папку и выбрать ее в качестве каталога вашего проекта.

В окне проводника теперь будет отображаться дерево каталогов проекта, что даст вам быстрый доступ к необходимым файлам и каталогам.

3: Настройка темы и шрифта редактора (опционально)

В настройке внешнего вида редактора нет острой необходимости, но иногда это бывает полезно – так можно сделать его более удобным для работы в долгосрочной перспективе. Разработчики много времени проводят в IDE (чем и является VS Code), и по этой причине важно убедиться, что шрифт редактора имеет соответствующий размер, что контрастность не утомляет глаза слишком быстро и код удобно читать.

Что касается удобочитаемости, здесь нет единой рекомендации. Советуем вам самостоятельно поэкспериментировать с разными темами и шрифтами, чтобы подобрать настройку, которая вам подходит.

Изменение темы VS Code

VS Code поставляется с несколькими темами, которые позволяют изменять цвета, используемые в интерфейсе редактора и при выделении кода. По умолчанию включены темный и светлый стили.

Перейдите в File -> Preferences -> Color Theme или нажмите CTRL+K+T, чтобы выбрать другую тему для VS Code.

Также можно установить расширения для темы, чтобы дополнительно настроить внешний вид VS Code. Если вы выполните поиск (CTRL + SHIFT + X), вы найдете несколько расширений для темы с разными стилями и цветами, включая цветовые схемы, перенесенные из других популярных редакторов и платформ.

Настройка шрифта

В целом, настройки шрифтов VS Code по умолчанию достаточно хороши – многие пользователи предпочитают не менять их. Но если вы хотите, вы можете настроить размер и тип шрифта редактора для повышения удобочитаемости.

Если вам нужно изменить размер шрифта или выбрать другой тип, вы можете перейти в меню File -> Preferences -> Settings, а затем выбрать Text Editor в левом меню. В открывшемся подменю нажмите Font. Этот раздел содержит настройки семейств и размеров шрифтов, которые вы можете выбрать по своему усмотрению.

Изменения немедленно сохраняются и применяются ко всем текущим открытым файлам.

Заключение

Visual Studio Code – это легкий, но мощный редактор кода, который можно настроить в соответствии с потребностями большинства разработчиков. В этом руководстве вы узнали, как установить и настроить расширение PHP Intelephense для работы над проектами PHP, как импортировать и создавать новые проекты в VS Code и как настроить внешний вид редактора, чтобы сделать процесс разработки более удобным.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *