Php Static Variables & Methods

Today, We want to share with you php static variable.In this post we will show you php static::, hear for php static constructor we will give you demo and example for implement.In this post, we will learn about when to use static methods php with an example.

Php Static Variables & Methods

A static variable is retrieved through your PHP userdefine class name followed by the scope resolution operator(::).

PHP Variable Scope Global Static & Local
PHP Variable Scope Global Static & Local

for Example:
( If userdefine class Name : Product and Variable name is : category)

Then you can retrieved it like this : Product::category.

self keyword with PHP OOP Static Methods like as scope resolution operator(::) is used to access “static variables” within userdefine class.

Also Read This 👉   PHP Laravel REST APIs Tutorial with MySQL

A Member simple function which is declared as “static” Keywords is retrieved through userdefine class name with “scope resolution operator”.

Also Read: PHP – Static Variables

Example 1: How to use static variables in a PHP function?

<?php
//definition of class.
	class Member
	{
		public static $i=1;
		public  $j=1;
		
		public function retriveMemberData()
		{
			return $this->j." value :  " . self::$i;
		}
		
		public  function setValue($a)
		{
			self::$i = $a;
			$this->j = $a;
		}
}

	 $Member = new Member();
	 $Member->setValue(10);
	 echo $Member->retriveMemberData();
	 
	 echo"<br>";
	 $Member1 = new Member();
	 echo $Member1->retriveMemberData();
	 
	 echo"<br>";
	 $Member2 = new Member();
	 echo $Member2->retriveMemberData();


?>

Free Live Chat for Any Issue

Example 2: When to use static vs instantiated classes in PHP?

<?php
//definition of class.
	class Member
	{
		public $name;
		public $points;
		public static $minimumPasswordLength = 6;
		
		public function Describe()
		{
			return $this->name . " is " . $this->points . " years old";
		}
		
		public static function ValidatePassword($password)
		{
			//if(strlen($password) >= self::$minimumPasswordLength)
			//	return true;
			//else
			//	return false;
		}
	
	public function set_name()
	{
		$this->name="Prakash";
		
	}
	public function get_name()
	{
		return $this->name;
		echo"<br>";
		
	}
	 public function set_points()
	{
		$this->points=45;
		
	}
	public function get_points()
	{
		return $this->points;
		echo"<br>";
		
	}
}
		
$password = "pakainfo";
if(Member::ValidatePassword($password))
    echo "Password is valid!";
else
    echo "Password is NOT valid!";

	 $Member = new Member();
	 echo $Member->set_name();
	 
	 echo"<br>";
	 echo $Member->get_name();
	 
	 echo $Member->set_points();
	 
	 echo"<br>";
	 echo $Member->get_points();
?>

I hope you get an idea about php static variable.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.