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
3
  • $test = new user(); Commented Apr 25, 2016 at 8:57
  • i need to use static function . Commented Apr 25, 2016 at 9:02
  • Possible duplicate of Call function inside __construct with php Commented Apr 25, 2016 at 10:03

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for solotion :)
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();

2 Comments

No i don't use . What's the similar way when use a static function ?
Then define it globally within class or outside of the class something like as const HI = 'hello'; or simply call the class within static function
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 Comment

Whats's the solotion ?i need this way !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.