【问题标题】:call a function from inside a function php oop从函数php oop内部调用函数
【发布时间】:2011-10-12 12:04:15
【问题描述】:

我想知道这是否可能,尽管我很相信也许有更好的方法。我有这个脚本结构:

class Mother {
    public function __construct() {
        // script here
    }

    public function writer() {
        if() {
            // if true
        } else {
            // call function hello
        }
    }

    public function hello() {
        echo "Hello there.";
    }
}

如何从 writer() 调用 hello()?谢谢。

【问题讨论】:

    标签: php oop class function call


    【解决方案1】:

    像这样

    public function writer() {
        $this->hello();
    }
    

    $this 是类的保留变量,任何实例化的类(通过new myClass 调用)都可以访问$this,但是如果您使用的是静态类,则需要将该函数定义为静态并使用static::myFunction 方法,例如:

    class exampleClass {
        public static function exampleFunc() {
            static::hello();
        }
        public static function hello() {
            echo "Hello!";
        }
    }
    exampleClass::exampleFunc();
    

    【讨论】:

    • 感谢您的快速反馈,请问这是最好的方法吗?
    • 是的,这几乎是唯一的方法,除非您静态使用该类,在这种情况下,请参阅我更新帖子中的示例,否则$this 是访问内部函数的最佳方法同一班。
    • 在短短几分钟内非常有启发性,非常感谢 Nexerus。
    【解决方案2】:
    // call function hello
    $this->hello();
    

    另外,您的其他函数在语法上是错误的。注意括号。

    public function writer() {
    public function hello() {
    

    【讨论】:

      【解决方案3】:

      在我的 PHP 5.3.4 安装中

      public function hello() { }
      

      似乎可以通过两种方式从另一个实例方法中获得

      $this->hello()
      self::hello()
      

      显然,

      $this
      

      将公共方法作为类方法调用时,对实例的引用将不可用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-03
        • 1970-01-01
        相关资源
        最近更新 更多