0

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
aldrin27
  • 3,407
  • 3
  • 29
  • 43
A.kapoor
  • 33
  • 4

3 Answers3

1

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();
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
1

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 
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
0

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.

Daan
  • 12,099
  • 6
  • 34
  • 51