如何在静态类中组合使用self和this


How to use self and this combined in a static class?

我想知道如何在"static"类中使用self::和$this组合?

<?php
class Test
{
    static private $inIndex = 0;
    static public function getIndexPlusOne()
    {
        // Can I use $this-> here?
        $this->raiseIndexWithOne();
        return self::inIndex
    }
    private function raiseIndexWithOne()
    {
        // Can I use self:: here?
        self::inIndex++;
    }
}
echo Test::getIndexPlusOne();

?>

我也在上面的代码中添加了问题,但我可以在非静态方法中使用self:吗?我可以在静态方法中用$this->来调用非静态函数吗?

谢谢!

您可以在非静态方法中使用self,但不能在static方法中使用$this

self总是指类,在类或对象上下文中也是如此
$this需要一个实例。

访问静态属性的语法为self::$inIndex BTW(需要$)。

你不能。静态方法不能与需要类实例的方法或属性(即非静态属性/方法)通信。

也许你在寻找singleton模式?

您可以在非静态方法中使用self::$inIndex,因为您可以从非静态方法访问静态内容。

不能在静态方法中使用$this->inIndex,因为静态方法未绑定到类的实例,因此静态方法中未定义$this。如果方法和属性也是静态的,则只能从静态方法访问它们。

这将起作用(http://codepad.org/99lorvq1)

<?php
class Test
{
    static private $inIndex = 0;
    static public function getIndexPlusOne()
    {
        // Can I use $this-> here?
        self::raiseIndexWithOne();
        return self::$inIndex;
    }
    private function raiseIndexWithOne()
    {
        // Can I use self:: here?
        self::$inIndex++;
    }
}
echo Test::getIndexPlusOne();

不能在静态方法中使用$this,因为没有实例