Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在静态类中使用self和this组合?_Php_Class_Static_This_Self - Fatal编程技术网

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

Php 如何在静态类中使用self和this组合?,php,class,static,this,self,Php,Class,Static,This,Self,我想知道如何在“静态”类中结合使用self::和$this 我在上面的代码中也添加了这些问题,但是我可以在非静态方法中使用self::吗?我可以在静态方法中使用$this->来调用非静态函数吗 谢谢 你不能。静态方法无法与需要类实例的方法或属性(即非静态属性/方法)通信 也许您正在寻找?您可以在非静态方法中使用self,但不能在静态方法中使用$this self总是指类,在类或对象上下文中也是如此。 $this需要一个实例 访问静态属性的语法是self::$INININDEXBTW(需要$)。

我想知道如何在“静态”类中结合使用self::和$this

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


谢谢

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


也许您正在寻找?

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

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


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

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

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

这样可以()


值得一提的是:现在单例被视为反模式。我仍然怀疑我的数据库类应该使用单例模式还是静态类。Singleton看起来更好,但您只能拥有1个。事实上,在未来我将不得不迁移我的数据库,我希望有2个实例,然后一个静态类会更好。其次,如果我在伟大的WWW.@pascalvgemert上看到基准测试,静态类要比单例模式快——如果你想要多个实例,你想用静态方法和属性实现什么?这些是“每个类”而不是“每个实例”。
<?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();
<?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();