【问题标题】:Returning value of a static methods静态方法的返回值
【发布时间】:2013-06-09 20:09:27
【问题描述】:

当我运行这段代码时

class Kernel
{
    private $settings = array();

    public function handle(Settings $conf)
    {
        $this->settings = $conf;
        return $this;
    }


    public function run()
    {
        var_dump($this->settings);
    }
}


class Settings
{
    public static function appConfig()
    {
        return array(
            'database' => array(
                'hostname' => 'localhost',
                'username' => 'root',
                'password' => 'test',
                'database' => 'testdb'
            )
        );
    }
}

$kernel = new Kernel;
$kernel->handle(Settings::appConfig())->run();

我得到错误

Catchable fatal error: Argument 1 passed to Kernel::handle() must be an instance of Settings, array given, called in....

这是否意味着类型提示仅适用于实例而不适用于静态方法?如果现在如何实现静态方法的类型提示?

【问题讨论】:

  • handle() 需要一个 Settings 类的对象,但您只是提供了一个简单的数组(appConfig() 的返回值)
  • appConfig的返回值不是类Settings的实例,不能给想要获取类型设置的方法一个类型数组

标签: php class oop static-methods


【解决方案1】:

好吧,错误文本解释了它。 你在这里传递一个数组:

$kernel->handle(Settings::appConfig())->run();

因为您的Settings::appConfig() 方法返回一个数组。 你必须在那里传递一个实例。

【讨论】:

    【解决方案2】:

    $conf 需要是 Settings 对象的实例以防止错误。

    句柄方法类提示意味着只接受设置类的对象实例。如果您想使用带有句柄方法的数组,则需要进行此更改。

    public function handle(Settings $conf)
    

    public function handle(array $conf)
    

    【讨论】:

      【解决方案3】:

      这会起作用:

      public function handle(array $conf)
      {
          $this->settings = $conf;
          return $this;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-20
        • 2018-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-23
        • 1970-01-01
        • 2021-12-31
        • 2020-07-30
        相关资源
        最近更新 更多