OPP PHP我无法弄清楚这里有什么问题

时间:2018-04-09 22:43:23

标签: php class oop

此代码不返回或输出任何内容,我无法弄清楚在这种情况下我做错了什么,请帮帮我

 class Foo
 {
    protected $bar;

   public function __construct()
   {
      $this->bar = 1;
   }

   public static function doSomething()
   {
    return $this->bar;
   }
}

1 个答案:

答案 0 :(得分:4)

您无法在$this方法中使用static。您可以删除static以制作Foo对象的方法。

class Foo
{
    protected $bar;

    public function __construct()
    {
        $this->bar = 1;
    }

    public function doSomething() // not static
    {
        return $this->bar;
    }
}

$foo = new Foo();
echo $foo->doSomething();

输出:

1

如果您想使用静态成员,可以执行以下操作:

class Foo
{
    static protected $bar;

    static public function init()
    {
        self::$bar = 1;
    }

    static public function doSomething()
    {
        return self::$bar;
    }
}

Foo::init();
echo Foo::doSomething();

输出:

1

或两者兼而有之:

<?php
class Foo
{
    protected $bar;

    public function __construct()
    {
        $this->bar = 1;
    }

    static public function doSomething()
    {
        return (new self())->bar;
    }
}

echo Foo::doSomething();

输出:

1