简体   繁体   English

对静态函数使用函数__construct()?

[英]use function __construct() for static functions?

I wanna to use this way but i have a problem , function __construct() dosn't work ? 我想使用这种方式,但是我有一个问题, function __construct()不起作用? 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(); 仅在初始化类时调用构造函数,例如$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 仅当您的PHP版本> = 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. 您必须在say_hi()方法内创建类user的新实例。 When you create the instance inside say_hi() method, it will call the constructor method and subsequently define the constant HI . 当您在say_hi()方法内创建实例时,它将调用构造函数方法并随后定义常量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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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