Основы синтаксиса

Содержание

Вставка в HTML

Когда PHP обрабатывает файл, он просто передаёт его текст, пока не встретит один из специальных тегов, который сообщает ему о необходимости начать интерпретацию текста как кода PHP. Затем он выполняет весь найденный код до закрывающего тега, говорящего интерпретатору, что далее снова идет просто текст. Этот механизм позволяет вам внедрять PHP-код в HTML - все за пределами тегов PHP остается неизменным, тогда как внутри - интерпретируется как код.

Существует четыре набора тегов, которые могут быть использованы для обозначения PHP-кода. Из них только два (<?php. . .?> и <script language="php">. . .</script>) всегда доступны; другие могут быть включены или выключены в конфигурационном файле php.ini. Хотя короткие теги и теги в стиле ASP могут быть удобны, они не так переносимы, как длинные версии. Кроме того, если вы намереваетесь вставлять PHP-код в XML или XHTML, чтобы соответствовать XML, вам следует использовать форму <?php. . .?>.

Теги, поддерживаемые PHP:

Пример #1 Способы вставки в HTML

1.  <?php echo("если вы хотите работать с документами XHTML или XML, делайте так\n"); ?>

2.  <? echo ("это простейшая инструкция обработки SGML\n"); ?>
    <?= выражение ?> Это синоним для "<? echo выражение ?>"
    
3.  <script language="php">
        
echo ("некоторые редакторы (например, FrontPage) не
              любят инструкции обработки"
);
    
</script>

4.  <% echo ("Вы можете по выбору использовать теги в стиле ASP"); %>
    <%= $variable; # Это синоним для "<% echo . . ." %>

Первый способ, <?php. . .?>, наиболее предпочтительный, так как он позволяет использовать PHP в коде, соответствующем правилам XML, таком как XHTML.

Второй способ не всегда доступен. Короткие теги доступны только когда они включены. Это можно сделать, используя функцию short_tags() (только в PHP 3), включив установку short_open_tag в конфигурационном файле PHP, либо скомпилировав PHP с параметром --enable-short-tags для configure. Даже если оно включено по умолчанию в php.ini-dist, использование коротких тегов не рекомендуется.

Четвертый способ доступен только если теги в стиле ASP были включены, используя конфигурационную установку asp_tags.

Замечание: Поддержка тегов в стиле ASP была добавлена в версии 3.0.4.

Замечание: Следует избегать использования коротких тегов при разработке приложений или библиотек, предназначенных для распространения или размещения на PHP-серверах, не находящихся под вашим контролем, так как короткие теги могут не поддерживаться на целевом сервере. Для создания переносимого, совместимого кода, не используйте короткие теги.

Закрывающий тег блока PHP-кода включает сразу следующий за ним перевод строки, если он имеется. Кроме того, закрывающий тег автоматически подразумевает точку с запятой; вам не нужно заканчивать последнюю строку кода в блоке точкой с запятой. Закрывающий тег PHP-блока в конце файла не является обязательным.

PHP позволяет использовать такие структуры:

Пример #2 Профессиональная вставка

<?php
if ($expression) { 
    
?>
    <strong>Это истина.</strong>
    <?php 
} else { 
    
?>
    <strong>Это ложь.</strong>
    <?php 
}
?>
Этот код работает так, как ожидается, потому что когда PHP встречает закрывающие теги ?>, он просто выводит все, что он находит до следующего открывающего тега. Приведенный здесь пример конечно придуманный, но для вывода больших блоков текста выход из режима интерпретации PHP обычно более эффективен, чем отправка всего текста через echo(), print() или что-либо подобное.

Коментарии

Brief Case of PHP Syntax
======================
php file:
=======
 
If you want your file to be interpreted as php then your file must end with that php and not with that html. php files can also have html, CSS, JavaScript in them.

php tag:
=======

php opening and closing tag is <?php ?> and php interpreter interpreted the code between opening and closing tag. But if your file entirely contain 100 percent php code then you do not need the closing tag and that is to make sure that no accidental  whitespace or new lines are added after the php closing tag which could mess up your website.

Semicolon:
=========

php closing tag will automatically  assume the semicolon on the last  line. 
So basically you do not need semicolon the Last line of php statement. This is useful when you are embedding php with html and it's just a single line in those case s you do not need the semicolon but if you have multiple lines though it's a good idea to stay consistent and just use the semicolon.

Php code execute:
================
You could execute your php script within your terminal. If you open xampp control panel and click on shell on here this will bring up the terminal. We need to cd into our project directory which is htdocs program with project name and then you could run php files using the php command and that will give you the output. So you could basically execute your php code in command line if you want.

You could also use print to print something which essentially is the same thing as echo.

Difference of echo and print:
==========================
Print has a return value of 1 for that reason here I give an example like
<?=  print "hello world" ?>
I do echo and then print that will print out hello world and then  append  one at the end because this expression itself return 1 this means that print could be used within expressions while echo can not for example if we did this the other way  print echo "hello world" and this would not work and we would get the syntax error.
Echo could print multiple values while print can not.
for example
echo "abc", "xyz";//works
print  "abc", "xyz";//does not works
Echo is marginally faster than print.

Variable
=======
Variable declared with dollar sign($).First character start with a-zA-Z_ and then other character from a-zA-Z_0-9.No space and no special character are allowed. This is a object so you do not assign $this. 

Variables in php are by default assign by value .Let me show you what I mean
so if we have a variable called x which equals to 1and then we have a variable y which equals o x and then  we change the value of x to 3 and then we print y what will be printed is 1 and not 3 that is because variables are assigned by value.On the other handif you actually wanted y to change whatever x cahnges then we need to assign variables by reference instead of value.  Assign a variable by reference,you need to add ampersand righ here so now y is equal to  reference variable x so anytime x cahnges the y will also change and now y is equal to 3.

Comments:
==========
There are two types of single line comments that are // your comments and  #your comments.
Multiline comments is /* comment here */. Nested multiple comments are not allowed.
2021-10-11 06:31:34
http://php5.kiev.ua/manual/ru/language.basic-syntax.html

    Поддержать сайт на родительском проекте КГБ