Work with Static Methods and Variables in PHP


Hi guys, In this article we are going to understand the concept of static methods and variables. Methods and variables can also be used and accessed if they are defined as static in a class. 

Concept

Static means the method or variable is accessible through the class definition and not just through objects. The ::operator allows you to refer to variables and methods on a class that doesn't yet have any instances or objects created for it.

Script for PHP

Using the -> and :: operators to call hypnotize:

<html>
<
body bgcolor="cyan">
<center>
<
h3> Static methods and variables in PHP <h3>
<
hr>
<?php
    class Cat {
    }
class Hypnotic_Cat extends Cat {
   
// Constructor
    function Hypnotic_Cat() {
    }
   
// This function must be called statically
    public static function hypnotize() {
echo ("The cat was hypnotized.");
     
return;
    }
}
// Hypnotize all cats
Hypnotic_Cat::hypnotize();
$hypnotic_cat =
new Hypnotic_Cat();
// Does nothing
$hypnotic_cat->hypnotize();
?>
</center>
</
body>
</html>

Save it as abc.php.

Output

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/abc.php 


static.gif

Note : When a method is called using the scope resolution operator (::), you can't use the $this object to refer to the object because there is no object.

Variables in PHP

Here I am going to explain variables in terms of php.

  • A variable name points to a location in memory that stores the data. There can be more than one variable name pointing to the same spot in memory.

  • The ampersand operator (&) is used to indicate that you're interested in the location in memory that a variable points to instead of its value.

  • PHP references allow you to create two variables to refer to the same content. There-fore, changing the value of one variable can change the value of another. This can make it very difficult to find errors in your code, since changing one variable also changes the other.

Syntax

Using a variable $svariable

<html>
<
body bgcolor="Orange">
<center>
<
h3> variables in PHP <h3>
<
hr>
<?php
$svariable = "Hello Friends!";
$sreference = &$some_variable;
$sreference =
"This is DEEPAK DWIJ!";
echo $svariable;
echo $sreference;
?>
</center>
</
body>
</html>

Save it as abc.php.

Output

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/abc.php 


varialse.gif

Thanks !

Up Next
    Ebook Download
    View all
    Learn
    View all