How to use class static methods in PHP

2 Answers

0 votes
class Test 
{
    public $pr = "Class property from class Test";
    public static $i = 0;
    
    public function __construct()
    {
        echo 'Constructor activated from class Test <br />';
    }
      
    public function __destruct()
    {
        echo '<br /> Destructor activated from class Test <br />';
    }
    
    protected function setProperty($val)
    {
        $this->pr = $val;
    }
    
    protected function getProperty()
    {
        return $this->pr;
    }
    public static function f()
    {
        return "i = " . ++self::$i . " <br />";
    }
}
  
class MyNewClass extends Test
{
    public function __construct()
    {
        parent::__construct(); 
        echo 'Constructor activated from class MyNewClass <br />';
    }

}

/* 
 static method can be accessed without first instantiating the class Test
 static values their stored values until the program end
 static method need to use static values  
*/
 
do
{
  // Call method f() without instantiating class Test
  echo Test::f();
} while ( Test::$i < 5 );







/*
run:

i = 1 
i = 2 
i = 3 
i = 4 
i = 5 

*/

 



answered Nov 4, 2015 by avibootz
0 votes
class Dog {
    public static function whatYouSay() {
         echo 'Woof! Woof!';
    }

    public static function speak() {
         self::whatYouSay();
    }
}

Dog::speak(); 

 
/*
run: 
  
Woof! Woof!
  
*/ 

 



answered Sep 7, 2017 by avibootz

Related questions

2 answers 266 views
1 answer 188 views
1 answer 196 views
1 answer 187 views
187 views asked Nov 4, 2015 by avibootz
3 answers 329 views
329 views asked Nov 3, 2015 by avibootz
...