loading...

Php Static Variables & Methods

pakainfocom profile image pakainfo ・2 min read

Php Static Variables & Methods

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

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.

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?

//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"
"; $Member1 = new Member(); echo $Member1->retriveMemberData(); echo"
"; $Member2 = new Member(); echo $Member2->retriveMemberData();

Example 2: When to use static vs instantiated classes in 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"
"; } public function set_points() { $this->points=45; } public function get_points() { return $this->points; echo"
"; } } $password = "pakainfo"; if(Member::ValidatePassword($password)) echo "Password is valid!"; else echo "Password is NOT valid!"; $Member = new Member(); echo $Member->set_name(); echo"
"; echo $Member->get_name(); echo $Member->set_points(); echo"
"; echo $Member->get_points();

I hope you get an idea about php static variable.

Discussion

pic
Editor guide