Raspberry Pi_Eng_24.4.3 Summary of PHP Syntax


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)
최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


24.4.3  Summary of PHP Syntax

 

If there is a static HTML tag on a web page, that page will always show the same content. However, if you use PHP to change the content of these HTML pages, the page will show the new changed contents. Like this, PHP plays a role to change the contents of a static HTML page into dynamic page. Therefore, according to the situation requested within the static HTML, a new HMTL is created and integrated with the existing static HTML tag to become an HTML document constituting a complete page.

 

For additional informations on PHP syntax, please refer to the following:

    http://php.net/docs.php  

    http://www.w3schools.com/php/default.asp  

 

24.4.3.1    Basic Structure of PHP

 

By using <?php  ?> tag form or <script language="php">  </script> tag form, PHP can be distinguished from regular HTML tags.  Anything can be used.

 

The following is the case to use <?php  ?> tag.

 

<!DOCTYPE html>

<html>

<body>

      <?php

          php-statement-1  ;

           php-statement-2  ;

      ?>

</body>

</html>

 

The following is the case to use <script language="php">   </script> tag.

 

<!DOCTYPE html>

<html>

<body>

      <script language="php">

          php-statement-1  ;

           php-statement-2  ;

      </script>

</body>

</html>

 

Documents containing PHP script are separated from the regular HTML document and stored in a PHP file. The default file extension for PHP file is ".php".

 

[Used Example]

<!DOCTYPE html>
<html>
<body>
           <h1>My first PHP page</h1>
           <?php
                       echo "Hello World!";
           ?>
</body>
</html>

 

<?php echo 'if you want to serve PHP code in XHTML or XML documents, use these tags'; ?>

 

<script language="php">

   echo 'some editors (like FrontPage) don't like processing instructions within these tags';

</script>

 

 


 

24.4.3.2    Rule of PHP Statement

 

   Statement end and Statement block

 

    All PHP statements end with a semi-colon (;).

    Use brace {  } to group multiple statements into a single unit.

 

 

   HTML and PHP script

 

    PHP files usually can contain HTML tags and PHP script at the same time.

    PHP script can be located anywhere in a document, and can be used multiple times in a document.

    PHP script can create a complete HTML document for itself, or it can be used to create a partial statement of HTML tag. 

    If closing tag "?>" is encountered in PHP, whaterver the following contents are, they are output as they are, and it continues until the next opening tag is encountered.

    If closing tag "?>" is in the middle of PHP condition statement, it determine whether result of conditional expression of the conditional statement is "True" or "False", and determine whether to output according to the condition in the conditional statement.

 

[Used Example]

Here is an example of PHP script associated with a conditional statement

 

<?php if ($expression == true): ?>

  This will show if the expression is true.

<?php else: ?>

  Otherwise this will show.

<?php endif; ?>

 

In the above example, the PHP interpreter excludes statements in the part where condition of conditional statement is not satisfied, even if they are outside PHP opening tag or closing tag. PHP interpreter jumps to the next part if the specified condition is not satisfied, so it excludes the content in the part that condition is not satisfied.

 

The following example shows a PHP script embedded inside HTML tag.

 

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

 

In the above example, PHP interpreter does not care even if PHP script is included in HTML tag, nor does it care about HTML opening tag after PHP closing "?>" tag. So, if "$highlight" is "True" in the above example, the contents as the first following will be output. Otherwise, the contents as the second following will be output. This manner allows you to selectively adjust the values of attributes within an HTML tag.

 

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

 

<html><body>
<p>This is a paragraph.</p>
</body></html>

 

 

   PHP case sensitivity

 

PHP's all keywords (if, else, while, echo, etc.), class, function, and user-defined function are not case-sensitive. However, all variables are case-sensitive.

 

[Used Example]

All three "echo" statements below will work fine.

 

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

 

In the following example, only the first "echo" statement will print the value of "$color" variable and the rest will not print normally. It is because "$color", "$COLOR", and "$coLOR" are treated as different variables.

 

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

 

 

   comment 규칙

 

The following three types of comment can be used in PHP:

    //               -- one-line comment

    #               -- one-line comment

    /*   */         -- multi-line comment

 

[Used Example]

Next is an example of comment in PHP

 

<?php
       // This is a single-line comment
       # This is also a single-line comment


       /*
       This is a multiple-lines comment block
       that spans over multiple
       lines
       */

       // You can also use comments to leave out parts of a code line
       $x = 5 /* + 15 */ + 5;

       echo $x;
?>

 

It is also possible to process comments in the following format.

 

<?php
       echo 'This is a test';      // This is a one-line c++ style comment
       /* This is a multi line comment
       yet another line of comment */
       echo 'This is yet another test';
       echo 'One Final Test';    # This is a one-line shell-style comment
?>

 


 

24.4.3.3    Variable

 

   Variable definition

 

You can use variable to store data in PHP. Variable is defined with name that begin with "$" symbol as follows.

 

$<variable-name>

 

The rules for PHP variable are as follows:

    Variable begin with "$" character, followed by the variable name.

    Variable name must begin with a letter or underscore (_) character, and must not begin with a digit.

    Variable name can only consist of alphabetic characters (A-z), numbers (0-9), and underscore (_).

    Variable names are case-sensitive. If their cases are different, they are treated as different variable.

 

 

   Data type of variable

 

The data type of PHP variable is not defined in advance, but it is automatically converted to the appropriate data type depending on the value stored.

 

 

   Reserved variable

 

The following variables are predefined and can not be used for other purposes.

    $GLOBALS References all variables available in global scope

    $_SERVER Server and execution environment information

    $_GET HTTP GET variables

    $_POST HTTP POST variables

    $_FILES HTTP File Upload variables

    $_REQUEST HTTP Request variables

    $_SESSION Session variables

    $_ENV Environment variables

    $_COOKIE HTTP Cookies

    $php_errormsg The previous error message

    $HTTP_RAW_POST_DATA Raw POST data

    $http_response_header HTTP response headers

    $argc The number of arguments passed to script

    $argv Array of arguments passed to script

 

 

   Scope of variable

 

In PHP, variables can be declared anywhere in the script. Scope of a variable means the range in which variables can be used or called. In PHP, there are local scope variable and global scope variable.

 

A variable declared within a function has local scope, and can only be used within a function.

 

A variable declared outside a function has global scope, which can be used outside the function by default, but can also be used within a function if necessary. You can use the global variable by declaring it as a global variable with "global" keyword in function. All global variables are stored in the "$GLOBALS" array, which you can use in functions in the form of "$GLOBALS ['variable']".

 

[Used Example]

Here is an example of a local variable.

 

<?php
function myTest() {
    $x = 5; // local scope
    echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>

 

 

The following is an example of using a global variable in a function.

 

<?php
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

 

The following is an example of using a global variable in a function in a different manner.

 

<?php
$x = 5;
$y = 10;

function myTest() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

 

 

 


 

24.4.3.4    Constant

 

Constant is a name assigned to a fixed value. The name of constant must begin with an alphabetic character or underscore (_), followed by any alphabetic character, number, or underscore freely. Constant name is not prefixed with "$" sign.

 

Constant can be used like variable. Unlike variable, it has property that can not be changed later if defined once, and it has global scope automatically in the entire script.

 

To define a constant, use "define()" function.

 

define( name,  value,  case-insensitive )

 

    name                     -- Specify the constant name

    value                     -- Specify a constant value

    case-insensitive        -- Specify whether a constant name is case-sensitive.

-- Default value is "False".

 

[Used Example]

Here is an example of constant.

 

<?php
// Valid constant names
define("FOO2",    "something else");
define("FOO_BAR", "something more");


// Invalid constant names
define("2FOO",    "something");

?>

 

 

The following is an example of defining a case-insensitive constant and using it inside a function.

 

<?php
define("GREETING", "Welcome to W3Schools.com!", true);


function myTest() {
    echo GREETING;
}
myTest();
?>

 

 


 

24.4.3.5    Data Type

 

PHP supports the following data types:

    String

    Integer

    Float (floating point numbers)

    Boolean

    Array

    Object

    NULL

    Resource

 

 

   String

 

A string is a series of characters, and it means text that characters are enclosed in quote.  Both single quote ('') and double quote ("") can be used without distinction.

 

[Used Example]

Here is an example of string data type.

 

<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

 

 

   Integer

 

An integer is an integer number without a decimal point. The range of this number is -2,147,483,648 to +2,147,483,647.

 

 

   Float (floating point numbers)

 

A float is a number with a decimal point or an exponent.

 

[Used Example]

Here is an example of float data type.

 

<?php

$x = 10.365;

var_dump($x);

?>

 

 

   Boolean

 

A boolean is a data representing two states, "True" and "False". When expressing a boolean value, it uses "True" or "False", not case-sensitive.

 

When converting the result of an expression to a boolean, the following cases are treated as "False", and all others are treated as "True". If it is a number, all nonzero numbers are regarded as "True", regardless of negative and positive number.

    boolean FALSE itself

    integer 0 (zero)

    float 0.0 (zero)

    empty string and string containing "0"

    array with zero element

    object without member variable (PHP 4 only)

    special type NULL (including unset variable)

    SimpleXML object created with empty tags

 

[Used Example]

Next is an example of various boolean data.

 

<?php

       var_dump((bool) "");          // bool(false)

       var_dump((bool) 1);           // bool(true)

       var_dump((bool) -2);          // bool(true)

       var_dump((bool) "that");     // bool(true)

       var_dump((bool) 2.3e5);       // bool(true)

       var_dump((bool) array(12));    // bool(true)

       var_dump((bool) array());      // bool(false)      àzero element

       var_dump((bool) "false");      // bool(true)       à not empty string

?>

 

 

   Array

 

An array is a data that stores multiple values in a single variable. The array of PHP is a data of type that key and value are internally linked together and sorted.

 

An array is defined using "array( )" statement, and if there are multiple arguments, each argument have to be separated with comma. From PHP 5.4, you can use "[  ]" format instead of "array( )" format. It is defined as follows.

 

array(

    key1 => value1,

    key2 => value2,

    key3 => value3,

    ...

)

 

An integer or a string can be used for key. Any value can be used for value. Key can be used optionally. If it is not specified, it is assigned the number that is incremented by "1" from the largest integer key value used immediately before.

 

[Used Example]

The following is an example of array that key is specified.

 

<?php

$array = array(

    "foo" => "bar",

    "bar" => "foo",

);

 

// as of PHP 5.4

$array = [

    "foo" => "bar",

    "bar" => "foo",

];

?>

 

The following is an example of an array that no key is specified.

 

<?php

$array = array("foo", "bar", "hello", "world");

var_dump($array);

?>

 

 

   Object

 

An object is a specially defined data type that contains data and data processing method together internally.

 

In PHP, an object must be declared in advance and used. When defining an object, a class of the object must be declared using "class" statement. A class is a data structure that contains property and method internally. If class is defined, for the predefined class, you create the actual object with "new" statement, and then perform the necessary operations on that object.

 

[Used Example]

Next, it defines class, create an object with "new" statement, and then do the necessary work.

 

<?php

class Car {

    function Car() {

        $this->model = "VW";

    }

}

 

// create an object

 $herbie = new Car();

 

// show object properties

echo $herbie->model;

?>