Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I call a normal (not static) class function by its name?

The below gives an error saying param 1 needs to be a valid callback. I don't want the function to be static, I want it to be a normal function, and all the examples I've seen so far had them static.

class Player
{
    public function SayHi() { print("Hi"); }
}

$player = new Player();

call_user_func($Player, 'SayHi');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
374 views
Welcome To Ask or Share your Answers For Others

1 Answer

The callback syntax is a little odd in PHP. What you need to do is make an array. The 1st element is the object, and the 2nd is the method.

call_user_func(array($player, 'SayHi'));

You can also do it without call_user_func:

$player->{'SayHi'}();

Or:

$method = 'SayHi';
$player->$method();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...