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
答案 0 :(得分: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.
答案 1 :(得分:0)
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();
答案 2 :(得分:0)
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