【问题标题】:call public method after static method in php在php中的静态方法之后调用公共方法
【发布时间】:2021-01-21 00:20:38
【问题描述】:

我有类示例,先调用静态方法,然后返回调用其他公共方法:

class foo{
 public static $var;
    public static function first()
    {
       self::$var = 1;
       return self::class;
    }  
    public function second()
    {
       return self::$var;
    }
}

我需要在静态方法示例之后调用公共方法:

foo::first()->second();

【问题讨论】:

  • 你不能将second 方法链接到string。所以它不会工作。返回first 上的实例,然后链接second。喜欢下面的答案
  • 有些东西可能值得一读 - PHP method chaining?
  • 这能回答你的问题吗? PHP method chaining?

标签: php class methods


【解决方案1】:

不,您不能这样做,因为从您的静态方法中您只返回字符串 - 类名。为了调用你的公共方法,你需要那个静态方法返回你的对象的一个​​实例,像这样

return new self();

【讨论】:

    猜你喜欢
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 2011-05-04
    • 2013-07-22
    • 1970-01-01
    • 2015-02-10
    相关资源
    最近更新 更多