Search code examples
phpclassconstruct

use function __construct() for static functions?


I wanna to use this way but i have a problem , function __construct() dosn't work ? Why ?

class user{

  function __construct(){
    define('HI', 'hello');
  }

  static function say_hi(){

     echo HI ;
  }
}

user::say_hi();// Out put should be : hello

Solution

  • You have to create a new instance of class user inside say_hi() method. When you create the instance inside say_hi() method, it will call the constructor method and subsequently define the constant HI.

    So your code should be like this:

    class user{
        function __construct(){
            define('HI', 'hello');
        }
    
        static function say_hi(){
            new user();
            echo HI ;
        }
    }
    
    user::say_hi();
    

    Output:

    hello