Как начать php код

How To Write Your First PHP Program

The “Hello, World!” program is a classic and time-honored tradition in computer programming. Serving as a complete first program for beginners and a good program to test systems and programming environments, “Hello, World!” illustrates the basic syntax of programming languages.

This tutorial will walk you through writing a “Hello, World!” program in PHP. You’ll also learn about opening and closing PHP code blocks within your code and using different types of comments in your code.

Prerequisites

You will need PHP installed as well as a local programming environment set up on your computer.

Writing the “Hello, World!” Program

To write the “Hello, World!” program, start by opening a command-line text editor, such as nano , and create a new file:

Once the text file opens up in the terminal window, type out the program:

Let’s break down the different components of the code.

All PHP code falls within a PHP Code Block, starting with .

echo is a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas and not delimited by parentheses. echo tells PHP to display or output whatever is included between echo and the ending semicolon ; .

Читайте также:  Java android context this

Between the echo and the ; is a sequence of characters — Hello, World! — that is enclosed in quotation marks. Any characters that are inside quotation marks are called a string.

After writing the program, hold down the CTRL key and press the X key to exit nano . When prompted to save the file, press Y .

Once you exit nano, you’ll return to your shell.

With that, you have written your “Hello, World!” program.

Running the “Hello, World!” Program

With your “Hello, World!” program written, you’re ready to run the program. Use the php command along with the name of the program file as follows:

Running the hello.php program that you just created will cause your terminal to produce the following output:

Let’s go over what the program did in more detail.

PHP executed the line echo «Hello, World!»; by calling the language construct echo . The string value of Hello, World! was passed to the construct.

In this example, the string Hello, World! is also called an argument since it is a value that is passed to another part of the code, such as a construct or a function.

The quotes that are on either side of Hello, World! were not output to the screen because they are used to tell PHP that this section of code contains a string. The quotation marks delineate where the string begins and ends.

Since the program ran successfully, you can now confirm that PHP is properly installed and that the program is syntactically correct. Before going any further in the code itself, let’s take a closer look at the PHP Code Block.

Working Outside the PHP Code Block

Within a .php file, anything outside of the PHP tags is treated as HTML or plain text. The PHP language was originally written as a way to extend the functionality of HTML. With this in mind, you may include multiple PHP code blocks throughout a file. Anything outside the code block will render as HTML or plain text.

Update your hello.php file:

Hi Sammy  echo "Hello, World!"; ?> How are you doing?  echo "Swimmingly!"; 

Save the file and rerun it:

Output
Hi Sammy Hello, World! How are you doing? Swimmingly!

Diving into the code, you’ll notice that Hi Sammy and How are you doing? are both outside the PHP code blocks and therefore render as plain text when running the program.

This file contains two PHP code blocks. The first code block includes both the starting and ending tags, while the second code block, being at the end of the file, leaves off the final closing tag.

Including the closing block tag ?> is not required. When ending a file with a PHP code block, it is recommended to leave off the closing tag. Any character, even a blank space, which is rendered after the closing tag will be output to the screen as HTML or plain text. This can cause unexpected consequences with the function of your application because certain functionality, such as a redirect, will not process if anything has been output to the browser. When writing a file that contains only PHP code, never include the closing PHP tag.

As code gets more complicated, like when splitting concepts over multiple code blocks, it can be beneficial to leave notes for ourselves and others. You can do this through the use of comments.

Adding Comments in PHP

A comment in code is a line that will not execute as a part of the program. Its only purpose is to be read by a human who is looking at the code. One thing that comes as a shock to many developers is how much time is spent reading code versus writing code. This means it’s essential to have code that is as easy to read as possible. You can accomplish this in a few ways:

  • Use coding standards. These are a collection of guidelines and best practices for organizing and formatting code clearly and consistently. In PHP, the most common coding standards are those developed by the PHP-FIG (Framework Interop Group).
  • Choose ease of reading over ease of writing. Use descriptive variables over short variables. It’s not about how many lines of code your write, but how long it will take someone to read those lines and understand what’s going on.
  • Comment for clarity. While it isn’t a hard and fast rule, if you’ve followed the previous two bullet points, your code should explain what is happening, while the comments explain why something is happening the way it is.

When writing comments in PHP, there are two types of comments: single-line comments and multiline comments. Single line comments can start at any point on a line and end at either the end of the line or the end of the code block, whichever comes first.

The most common way to start a single-line comment is with the double forward slash ( // ), although PHP also recognizes a hash sign ( # ) as a valid start to a single-line comment:

Hi Sammy  echo "Hello"; //, World!"; ?> How are you doing?  echo "Swimmingly!"; // other options: Floating along 

Save the file and run it again:

Output
Hi Sammy Hello How are you doing? Swimmingly!

The first comment starts in the middle of a line. A closing quote and semicolon were added after «Hello» and the rest of the line was commented out. Commenting out one or more lines of code is often used in debugging to test how the code responds if certain elements are removed.

You use a second comment to give a secondary option for an answer. The next step in your project may be to respond with one of several different options each time you execute the application. The comment is used as a reminder for other options that could be added.

Multiline comments start with /* and end with */ . The PHP interpreter will ignore any text or code within those characters. To provide more options, let’s change the last line to a multi-line comment:

Hi Sammy  echo "Hello"; //, World!"; ?> How are you doing?  echo "Swimmingly!"; /* When responding with one of a number of answers, here are some other options: * Floating along * Fin-tastic * Going with the flow * Treading water * Swamped */ 

Using a multi-line comment gives more room to add detail or formatting to once again make the code, and the intention of the code, easier to understand. This multi-line comment includes line breaks and added * as a delineator for a list. The */ combination signifies the end of our comment block.

Using DocBlocks for Documentation

There is a special type of multi-line comment called a DocBlock. This is a unique way of documenting the functionality of a particular file, class, method, or other structural elements. Although a DocBlock starts and ends like any other multi-line comment /* */ , they are designed to give specific detail for working with an element. Not only do these details provide an overview of the code for developers, but they may also be used by a code editor (or IDE) to provide suggestions and validation.

A DocBlock consists of several parts. The first is a brief summary to introduce the element and a longer description if more context is needed.

The final section that makes a DocBlock unique is for tags and annotations. These provide a way to succinctly and uniformly provide meta-information about the associated element. Tags can, for example, describe the type of information that is accepted or returned by a method or function. It may also provide details about the author or copyright of a file:

 /** * DocBlock example * * @author Sammy */ . 

While you should strive to write code that is clear and easy to follow, adding clarifying comments can add additional context that will increase the understanding of the code and the choices behind the code.

Conclusion

In this tutorial, you have written the “Hello, World!” program in PHP. You learned about opening and closing PHP code blocks within your code and using different comments to clarify and add context as your code gets more complicated. From here, you can continue learning by following the How To Work with Strings in PHP tutorial.

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

Tutorial Series: How To Code in PHP

PHP banner image

PHP is a popular server scripting language known for creating dynamic and interactive web pages.

Источник

Как начать php код

1. Синтаксис

Код в PHP заключается в открывающий теги. Согласно стандарту кодирования PSR-12, закрывающий тег должен быть опущен в файлах, содержащих только код PHP . В конце строки ставят разделитель строк – точку с запятой ; . Если забыть поставить разделитель, то следующая строка кода соединится с предыдущей и интерпретатор PHP выдаст ошибку.

Выведем на экран строку Hello World (заключена в кавычки) с помощью команды echo :

Рис. 2. Условный оператор if в PHP

Оператор if выполняет код, если выполняется условие. В противном случае выполняется код после else, который переводится, как «иначе», «в другом случае».

Рис. 3. Цикл while в PHP

Оператор while выполняет код до тех пор, пока значение условия не станет ложным.

Рис. 4. Цикл for в PHP

Когда нам известно количество итераций, вместо цикла while лучше использовать цикл for .

Рис. 5. Индексы элементов в массиве PHP

Массивы – упорядоченная коллекция элементов с доступом по индексу или ключу. Индексный массив создается двумя способами:

Рис. 6. Запуск встроенного в PHP веб-сервера

Если мы получили ошибку 404, значит сервер запущен.

XAMPP

Скачаем и установим XAMPP . В папке C:\xampp\htdocs\ создадим папку нашей странички page . Запустим веб-сервер Apache, кликнув по кнопке Start . Узнаем версию PHP, введя в консоли (Shell) команду php -v .

Рис. 7. Запуск сервера с помощью XAMPP

Проверим, запущен ли сервер, перейдя по адресу http://localhost/ . Если появилось приветственное сообщение, значит сервер запущен.

Рис. 8. Запуск сервера с помощью XAMPP на Windows

14. Собираем страничку

Теперь создадим несколько PHP-файлов, из которых соберем страничку. Перейдем в папку page и создадим четыре файла: index.php , header.php , body.php , footer.php .

Структура простого HTML-документа выглядит следующим образом:

Рис. 9. HTML-страница, собранная из php-файлов

Литература

  • Робин Никсон. Создаем динамические веб-сайты с помощью PHP, MySQL, JavaScript, CSS и HTML5;
  • Котеров, Симдянов. PHP 7;
  • Веллинг, Томсон. Разработка веб-приложений с помощью PHP и MySQL;

Шпаргалки

YouTube-каналы и курсы

Бесплатные курсы на русском языке:

  • Основы php с нуля. Новейший курс 2020 – двадцать четыре урока от основ до регулярных выражений и функций;
  • Базовый курс по PHP 7 – узнаете про базовые понятия, GET-параметры, методы, функции и ООП;
  • Учим PHP за 1 Час – основы за полтора часа;
  • Изучение PHP для начинающих – научитесь работать с массивами, подключать файлы, обрабатывать формы, работать с куки и базой данных MySQL;
  • Уроки PHP 7 – много уроков по ООП;
  • PHP для начинающих – курс на Stepik для начинающих разработчиков, не требует специальных знаний;
  • PHP – первое знакомство – азы программирования на PHP (Stepik).

PHP в «Библиотеке Программиста»

  • подписывайтесь на тег PHP , чтобы получать уведомления о новых статьях;
  • телеграм-канал «Библиотека пхпшника»;
  • книги по программированию в нашем телеграм-канале «Книги для программистов».

Итог

  • вы познакомились с синтаксисом PHP и типами данных;
  • узнали, как работают условные операторы и циклы;
  • запустили веб-сервер в Ubuntu и Windows;
  • собрали страничку HTML из файлов PHP.

Источник

Оцените статью