【问题标题】:How to use self and this combined in a static class?如何在静态类中使用 self 和 this ?
【发布时间】:2012-03-28 11:15:35
【问题描述】:

我想知道如何在“静态”类中使用 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-> 来调用非静态函数吗?

谢谢!

【问题讨论】:

    标签: php class static this self


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      也许您正在寻找singleton pattern

      【讨论】:

      • 值得一提:现在单例被视为反模式。
      • 我仍然怀疑是否应该为我的数据库类使用单例模式或静态类。单例看起来更好,但你只能有 1 个。事实上,将来我将不得不迁移我的数据库,我希望有 2 个实例,然后一个静态类会更好。如果我在伟大的 WWW 上看到基准测试,那么静态类比单例模式更快。
      • @pascalvgemert - 如果你想要多个实例,你想用静态方法和属性来实现什么?这些是“每个类”而不是“每个实例”。
      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        这会起作用 (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,因为没有实例

        【讨论】:

          猜你喜欢
          • 2015-07-14
          • 1970-01-01
          • 1970-01-01
          • 2016-06-10
          • 2015-12-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多