You get a bonus - 1 coin for daily activity. Now you have 1 coin

PHP syntax

Lecture



General concepts

PHP language is specifically designed for web programming. PHP combines the advantages of C and Perl and is very easy to learn and has significant advantages over traditional programming languages.

PHP syntax is very similar to the syntax of the C language and is largely borrowed from languages ​​such as Java and Perl.

Programmer C will very quickly master the PHP language and will be able to use it with maximum efficiency.
In principle, in PHP there are almost all operators and functions available in standard GNU C (or their analogs), for example, there are cycles (while, for), choice operators (if, switch), functions for working with the file system and processes (fopen, * dir, stat, unlink, popen, exec), input / output functions (fgets, fputs, printf) and many others ...

The purpose of this section is a brief introduction to the basics of the PHP syntax. For more information on specific components of the PHP syntax, see the relevant sections.

PHP and HTML

The syntax of any programming language is much easier to “feel” with examples, rather than using some kind of diagrams and charts. Therefore, we give an example of a simple PHP script:

<html>
<head>
<title>Пример</title>
</head>
<body>

<?
echo "Привет, я - скрипт PHP!";
?>

</body>
</html>

You have probably already noticed that this is a classic script that starts learning a programming language.

Please note that the HTML code is correctly processed by the PHP interpreter.

The interpreter also supports short code inclusion tags.
so <? php phpinfo (); ?>
or so <? phpinfo (); ?>


to support it, you need to enable in the short_open_tag settings
in one of the files
/etc/php5/cli/php.ini
/etc/php5/cgi/php.ini
/etc/php5/fpm/php.ini

and restart webserver

The beginning of the script may puzzle you: is this a script? Where are the HTML tags <html> and <body>? This is where the main feature (by the way, extremely convenient) of the PHP language lies: The PHP script may not differ at all from a regular HTML document.

Go ahead. You probably guessed that the script code itself begins after the opening tag <? and ends closing ?> . So, between these two tags, the text is interpreted as a program, and does not fit into the HTML document. If the program needs to display something, it should use the echo operator.

So, PHP is designed so that any text that is located outside of program blocks, limited <? and ?> , is output to the browser directly. This is the main feature of PHP, in contrast to Perl and C, where the output is carried out only using standard operators.

Separation of instructions

Instructions are separated in the same way as in C or Perl - each expression ends with a semicolon.

The closing tag (?>) Also implies the end of the instruction, so the following two code fragments are equivalent:

<?php
echo "Это тест";
?>

<?php echo "Это тест" ?>

Comments in PHP scripts

Writing almost any script can not do without comments.

PHP supports comments in the style of 'C', 'C ++' and Unix shells. For example:

<?php
echo "Это тест"; // Это однострочный комментарий в стиле c++
/* Это многострочный комментарий
еще одна строка комментария */
echo "Это еще один тест";
echo "Последний тест"; # Это комментарий в стиле оболочки Unix
?>

Single-line comments go only to the end of the line or the current block of PHP code, depending on what goes before them.

<h1>Это <?php # echo "простой";?> пример.</h1>
<p>Заголовок вверху выведет 'Это пример'.

Be careful not to have nested 'C'-comments, they may appear while commenting on large blocks:

<?php
/*
echo "Это тест"; /* Этот комментарий вызовет проблему */
*/
?>

Single-line comments go only to the end of the line or the current block of PHP code, depending on what goes before them. This means that the HTML code after //?> WILL BE printed:?> Takes it out of PHP mode and returns to HTML mode, but // does not allow it.

PHP variables

Variable names are denoted by $ . The same “Hello, I am a PHP script!” Can be obtained as follows:

<? php
$ message =   "Привет, я - скрипт PHP!" ;
echo $ message ;
?>

Details on variables in PHP here.

Data Types in PHP

PHP supports eight simple data types:

Four scalar types:

- boolean (binary data)
- integer (integers)
- float (floating point numbers or 'double')
- string (strings)

Two mixed types:

- array (arrays)
- object (objects)

And two special types:

resource
NULL ("empty")

There are also several pseudotypes:

- mixed
- number (s)
- callback

Details on data types in PHP here.

Php expressions

The main forms of expressions are constants and variables. For example, if you write $ a = 100, you assign $ 100 to $ a:

$a = 100;

In the example above, $ a is a variable, = is an assignment operator, and 100 is expressions. Its value is 100.

An expression can also be a variable if it is associated with a specific value:

$x = 7;
$y = $x;

In the first line of the considered example, the expression is a constant 7, and in the second line is the variable $ x, since it was previously assigned the value 7. $ y = $ x is also an expression.

Details on php expressions can be found here.

PHP operators

The operator is called something consisting of one or more values ​​(expressions, if we speak in the jargon of programming), which can be calculated as a new value (thus, the whole structure can be considered as an expression).

Examples of PHP statements:

Assignment Operators:

<?php

$a = ($b = 4) + 5; // результат: $a установлена значением 9, переменной $b присвоено 4.

?>

Combined operators:

<?php

$a = 3;
$a += 5; // устанавливает $a значением 8, аналогично записи: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // устанавливает $b строкой "Hello There!", как и $b = $b . "There!";

?>

String Operators:

<?php
$a = "Hello ";
$b = $a . "World!"; // $b содержит строку "Hello World!"

$a = "Hello ";
$a .= "World!"; // $a содержит строку "Hello World!"
?>

There are also logical operators and comparison operators, but they are usually considered in the context of language control constructs.

Detailed information on PHP operators can be found here .

PHP control structures

The main constructs of the PHP language are:

  1. Conditional statements (if, else);
  2. Loops (while, do-while, for, foreach, break, continue);
  3. Switch constructions (switch);
  4. Declare constructs;
  5. Constructions return values ​​(return);
  6. Constructions of inclusions (require, include).

Examples of PHP language constructs:

<?php
if ($a > $b) echo "значение a больше, чем b";
?>

The given example clearly shows the use of the if construct together with the comparison operator ($ a> $ b).

In the following example, if the variable $ a is not equal to zero, the string "the value of a is true (true) will be output, that is, the interaction of the if statement (construct) with the logical operator is shown:

<?php
if ($a) echo "значение a истинно (true) ";
?>

Here is an example of a while loop:

<? php
$ x = 0 ;
while   ($ x ++< 10 ) echo $ x ;
// Выводит 12345678910
?>

Information on all PHP control structures can be found here.

PHP user functions

In any programming language there are subroutines. In C, they are called functions, in assembly language, subroutines, and in Pascal, there are two types of subroutines: procedures and functions.

In PHP, such routines are custom functions .

A subprogram is a specially designed fragment of a program that can be accessed from anywhere within the program. Subroutines greatly simplify the life of programmers, improving the readability of the source code, as well as shortening it, since individual code fragments do not need to be written several times.

Here is an example of a user-defined function in PHP:

<?php

function funct() {
$a = 100;
echo "<h4>$a</h4>";
}
funct();

?>

The script displays 100:

100

You can pass arguments to user-defined functions in PHP and get return values ​​from functions.

Detailed information on PHP user functions can be found here.

Built-in (standard) PHP functions

PHP contains a huge number of built-in functions that can perform tasks of different levels of complexity.

The PHP.SU portal contains a complete reference for standard PHP functions.

OOP and PHP

PHP has fairly good support for object-oriented programming (OOP).

In PHP, you can create classes of different levels, objects, and rather flexibly operate with them.

Here is an example of a PHP class and its use:

<? php
// Создаем новый класс Coor:
class Coor {
// данные (свойства):
var   $ name ;

// методы:
  function Getname ()   {
echo "<h3>John</h3>" ;
  }

}

// Создаем объект класса Coor:
$ object = new Coor ;
// Получаем доступ к членам класса:
$ object -> name =   "Alex" ;
echo $ object -> name ;
// Выводит 'Alex'
// А теперь получим доступ к методу класса (фактически, к функции внутри класса):
$ object -> Getname ();
// Выводит 'John' крупными буквами
?>

Details on classes and OOP in PHP can be found in other sections.

So, briefly describing the syntax, you can describe the wonderful language PHP. For detailed information on each specific issue, use the relevant sections and articles.

See also Alternative syntax for control structures ¶

created: 2016-01-25
updated: 2021-03-13
170



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)