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.

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 !