PHP Basic

By ukmodak | March 31st 2024 10:36:23 AM | viewed 215 times

PHP Case Sensitivity:

In PHP, keyword (e.g., echo, if, else, while), functions, user-defined functions, classes are not case-sensitive.

However, all variable names are case-sensitive.

echo and print Statements

We frequently use the echo statement to display the output. There are two basic ways to get the output in PHP:

  • echo
  • print

echo and print are language constructs, and they never behave like a function. Therefore, there is no requirement for parentheses. However, both the statements can be used with or without parentheses. We can use these statements to output variables or strings.

Difference between echo and print

echo
  • echo is a statement, which is used to display the output.
  • echo can be used with or without parentheses.
  • echo does not return any value.
  • We can pass multiple strings separated by comma (,) in echo.
  • echo is faster than print statement.
print
  • print is also a statement, used as an alternative to echo at many times to display the output.
  • print can be used with or without parentheses.
  • print always returns an integer value, which is 1.
  • Using print, we cannot pass multiple arguments.
  • print is slower than echo statement.
You can pass multiple arguments separated by a comma (,) in echo. It will not generate any syntax error.
     <?php  
         $fname = "Gunjan";  
         $lname = "Garg";  
         echo "My name is: ".$fname,$lname;  
    ?>  
	Output: ok
 
It will generate a syntax error because of multiple arguments in a print statement.
     <?php  
        $fname = "Gunjan";  
        $lname = "Garg";  
        print "My name is: ".$fname,$lname;  
    ?> 
Output: error
 
echo statement does not return any value. It will generate an error if you try to display its return value.
     <?php  
       $lang = "PHP";  
       $ret = echo $lang." is a web development language.";  
       echo "
"; echo "Value return by print statement: ".$ret; ?> Output: error
As we already discussed that print returns a value, which is always 1.
     <?php  
       $lang = "PHP";  
       $ret = print $lang." is a web development language.";  
       print "
"; print "Value return by print statement: ".$ret; ?> Output: ok

PHP Variables

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know about variables:

As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to its correct datatype

After declaring a variable, it can be reused throughout the code.

Assignment Operator (=) is used to assign the value to a variable.

$variablename=value; 

Rules for declaring PHP variable:

  • A variable must start with a dollar ($) sign, followed by the variable name.
  • It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
  • A variable name must start with a letter or underscore (_) character.
  • A PHP variable name cannot contain spaces.
  • One thing to be kept in mind that the variable name cannot start with a number or special symbols.
  • PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
Let's see the example to store string, integer, and float values in PHP variables.
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str 
"; echo "integer is: $x
"; echo "float is: $y
";
Invalid variable
$4c="hello";//number (invalid)  
$*d="hello";//special symbol (invalid)  
echo "$4c 
$*d";

PHP Variable Scope

The scope of a variable is defined as its range in the program under which it can be accessed. In other words, "The scope of a variable is the portion of the program within which it is defined and can be accessed."

PHP has three types of variable scopes:

  • Local variable
  • Global variable
  • Static variable
Local variable

The variables that are declared within a function are called local variables for that function. These local variables have their scope only in that particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local scope.

A variable declaration outside the function with the same name is completely different from the variable declared inside the function. Let's understand the local variables with the help of an example:

   
        function mytest()  
        {  
            $lang = "PHP";  
            echo "Web development language: " .$lang;  
        }  
        mytest();  
        //using $lang (local variable) outside the function will generate an error  
        echo $lang;  
Global variable

The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program. To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the function.

 $name = "Sanaya Sharma";        //Global Variable  
    function global_var()  
    {  
        global $name;  
        echo "Variable inside the function: ". $name;  
        echo "
"; } global_var(); echo "Variable outside the function: ". $name;
Using $GLOBALS instead of global

Another way to use the global variable inside the function is predefined $GLOBALS array.

$num1 = 5;      //global variable  
    $num2 = 13;     //global variable  
    function global_var()  
    {  
            $sum = $GLOBALS['num1'] + $GLOBALS['num2'];  
            echo "Sum of global variables is: " .$sum;  
    }  
    global_var(); 
Sum of global variables is: 18	

If two variables, local and global, have the same name, then the local variable has higher priority than the global variable inside the function.

    $x = 5;  
    function mytest()  
    {  
        $x = 7;  
        echo "value of x: " .$x;  
    }  
    mytest(); 

Value of x: 7	
Static variable

Static variables exist only in a local function, but it does not free its memory after the program execution leaves the scope. Understand it with the help of an example:

    function static_var()  
    {  
        static $num1 = 3;       //static variable  
        $num2 = 6;          //Non-static variable  
        //increment in non-static variable  
        $num1++;  
        //increment in static variable  
        $num2++;  
        echo "Static: " .$num1 ."
"; echo "Non-static: " .$num2 ."
"; } //first function call static_var(); //second function call static_var(); Static: 4 Non-static: 7 Static: 5 Non-static: 7

PHP $ and $$ Variables

The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

$x = "abc";  
$$x = 200;  
echo $x."
"; echo $$x."
"; echo $abc; // $$x = $abc abc 200 200

Constants

PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways:

  • Using define() function
  • Using const keyword

Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of define() function in PHP.

    define(name, value, case-insensitive)  
	
	define("MESSAGE","Hello JavaTpoint PHP");  
   echo MESSAGE;  
   
   output:Hello JavaTpoint PHP
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive  
echo MESSAGE;  
echo message;  

output:Hello JavaTpoint PHP
Notice: Use of undefined constant message - assumed 'message' 
in C:\wamp\www\vconstant3.php on line 4
message
PHP constant: const keyword

PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a function. The constant defined using const keyword are case-sensitive.

const MESSAGE="Hello const by JavaTpoint PHP";  
echo MESSAGE;  

output:Hello const by JavaTpoint PHP
Constant() function

There is another way to print the value of constants using constant() function instead of using the echo statement.

constant (name)

define("MSG", "JavaTpoint");  
echo MSG, "
"; echo constant("MSG"); //both are similar output: JavaTpoint JavaTpoint
Constant vs Variables
Constant Variables
Once the constant is defined, it can never be redefined. A variable can be undefined as well as redefined easily.
A constant can only be defined using define() function. It cannot be defined by any simple assignment. A variable can be defined by simple assignment (=) operator.
There is no need to use the dollar ($) sign before constant during the assignment. To declare a variable, always use the dollar ($) sign before the variable.
onstants do not follow any variable scoping rules, and they can be defined and accessed anywhere. Variables can be declared anywhere in the program, but they follow variable scoping rules.
Constants are the variables whose values can't be changed throughout the program. The value of the variable can be changed.
By default, constants are global. Variables can be local, global, or static.
Magic Constants

Magic constants are the predefined constants in PHP which get changed on the basis of their use. They start with double underscore (__) and ends with double underscore

They are similar to other predefined constants but as they change their values with the context, they are called magic constants.

There are nine magic constants in PHP. In which eight magic constants start and end with double underscores (__).

  1. __LINE__
  2. __FILE__
  3. __DIR__
  4. __FUNCTION__
  5. __CLASS__
  6. __TRAIT__
  7. __METHOD__
  8. __NAMESPACE__
  9. ClassName::class
  10. All of the constants are resolved at compile-time instead of run time, unlike the regular constant. Magic constants are case-insensitive.

    __LINE__

    It returns the current line number of the file, where this constant is used.

     echo "

    Example for __LINE__

    "; // print Your current line number i.e;4 echo "You are at line number " . __LINE__ . "

    "; output:You are at line number 4
    __FILE__

    This magic constant returns the full path of the executed file, where the file is stored. If it is used inside the include, the name of the included file is returned.

      echo "

    Example for __FILE__

    "; //print full path of file with .php extension echo __FILE__ . "

    "; output:D:\xampp\htdocs\program\magic.php
    __DIR__

    It returns the full directory path of the executed file. The path returned by this magic constant is equivalent to dirname(__FILE__). This magic constant does not have a trailing slash unless it is a root directory.

      echo "

    Example for __DIR__

    "; //print full path of directory where script will be placed echo __DIR__ . "

    "; //below output will equivalent to above one. echo dirname(__FILE__) . "

    "; output:D:\xampp\htdocs\program
    __FUNCTION__

    This magic constant returns the function name, where this constant is used. It will return blank if it is used outside of any function.

      echo "

    Example for __FUNCTION__

    "; //Using magic constant inside function. function test(){ //print the function name i.e; test. echo 'The function name is '. __FUNCTION__ . "

    "; } test(); //Magic constant used outside function gives the blank output. function test_function(){ echo 'Hie'; } test_function(); //give the blank output. echo __FUNCTION__ . "

    "; output:The function name is test
    __CLASS__

    It returns the class name, where this magic constant is used. __CLASS__ constant also works in traits.

      echo "

    Example for __CLASS__

    "; class JTP { public function __construct() { ; } function getClassName(){ //print name of the class JTP. echo __CLASS__ . "

    "; } } $t = new JTP; $t->getClassName(); //in case of multiple classes class base { function test_first(){ //will always print parent class which is base here. echo __CLASS__; } } class child extends base { public function __construct() { ; } } $t = new child; $t->test_first(); output:JTP
    __TRAIT__

    This magic constant returns the trait name, where it is used.

      echo "

    Example for __TRAIT__

    "; trait created_trait { function jtp(){ //will print name of the trait i.e; created_trait echo __TRAIT__; } } class Company { use created_trait; } $a = new Company; $a->jtp(); output:created_trait
    __METHOD__

    It returns the name of the class method where this magic constant is included. The method name is returned the same as it was declared.

      echo "

    Example for __METHOD__

    "; class method { public function __construct() { //print method::__construct echo __METHOD__ . "

    "; } public function meth_fun(){ //print method::meth_fun echo __METHOD__; } } $a = new method; $a->meth_fun(); output: method:: construct method:: meth_fun
    __NAMESPACE__

    It returns the current namespace where it is used.

      echo "

    Example for __NAMESPACE__

    "; class name { public function __construct() { echo 'This line will print on calling namespace.'; } } $class_name = __NAMESPACE__ . '\name'; $a = new class_name; output: This line will print on calling namespace.
    ClassName::class:

    This magic constant does not start and end with the double underscore (__). It returns the fully qualified name of the ClassName. ClassName::class is added in PHP 5.5.0. It is useful with namespaced classes.

       namespace Technical_Portal;  
        echo "

    Example for CLASSNAME::CLASS

    "; class javatpoint { } echo javatpoint::class; //ClassName::class output: Technical_Portal\javatpoint

    PHP Comments

    PHP comments can be used to describe any line of code so that other developer can understand the code easily. It can also be used to hide any code.

    PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style (Unix shell style) comments.

    Single Line Comments
     / this is C++ style single line comment  
    # this is Unix Shell style single line comment  
    echo "Welcome to PHP single line comments";  
     
    Multi Line Comments

    In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */. Let's see a simple example of PHP multiple line comment.

     /* 
    Anything placed 
    within comment 
    will not be displayed 
    on the browser; 
    */  
    echo "Welcome to PHP multi line comment";    
     
bONEandALL
Visitor

Total : 20972

Today :26

Today Visit Country :

  • Germany
  • United States
  • Singapore
  • China
  • United Kingdom
  • South Korea
  • Czechia