简体   繁体   中英

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

A constructor is only called when initializing a class for example $user = new user(); . When calling a static function a class isn't initialized thus the constructor is not called.

You can do this way only if you have PHP version >= 7

class User{

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

  static function say_hi(){

     echo HI ;
  }
}

(new User())::say_hi();

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM