PHP 在同一个类中使用 call_user_func 调用实例方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4288105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:32:26  来源:igfitidea点击:

PHP Call a instance method with call_user_func within the same class

php

提问by Fred

I'm trying to use call_user_functo call a method from another method of the same object, e.g.

我正在尝试使用call_user_func从同一对象的另一个方法调用一个方法,例如

class MyClass
{
    public function __construct()
    {
        $this->foo('bar');
    }
    public function foo($method)
    {
        return call_user_func(array($this, $method), 'Hello World');
    }

    public function bar($message)
    {
        echo $message;
    }
}

new MyClass;Should return 'Hello World'...

new MyClass;应该返回'Hello World'...

Does anyone know the correct way to achieve this?

有谁知道实现这一目标的正确方法?

Many thanks!

非常感谢!

回答by Paul Dixon

The code you posted should work just fine. An alternative would be to use "variable functions"like this:

您发布的代码应该可以正常工作。另一种方法是使用“变量函数”,如下所示:

public function foo($method)
{
     //safety first - you might not need this if the $method
     //parameter is tightly controlled....
     if (method_exists($this, $method))
     {
         return $this->$method('Hello World');
     }
     else
     {
         //oh dear - handle this situation in whatever way
         //is appropriate
         return null;
     }
}

回答by Matt Williamson

This works for me:

这对我有用:

<?php
class MyClass
{
    public function __construct()
    {
        $this->foo('bar');
    }
    public function foo($method)
    {
        return call_user_func(array($this, $method), 'Hello World');
    }

    public function bar($message)
    {
        echo $message;
    }
}

$mc = new MyClass();
?>

This gets printed out:

这被打印出来:

wraith:Downloads mwilliamson$ php userfunc_test.php 
    Hello World

回答by Gordon

new MyClass; Should return 'Hello World'...

新的MyClass;应该返回'Hello World'...

A constructor does not return anything.

构造函数不返回任何内容。