Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/293.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 static::和$this:'之间的差异:_Php_Static_This_Self - Fatal编程技术网

Php static::和$this:'之间的差异:

Php static::和$this:'之间的差异:,php,static,this,self,Php,Static,This,Self,我知道静态::和self::之间有区别,就像在这个例子中(从) 产生 '一,静态::'=>'测试1' 'two,static::'=>'test2' 'one,self::'=>'test1' 'two,self::'=>'test1' '一,$this::'=>'测试1' 'two,$this::'=>'test2' 因此self指的是定义方法的类,但在这些非静态方法中,$this:和static::之间没有区别。实际上没有区别。:功能随着时间的推移而扩展,因此左侧不需要是类文字,也可以是

我知道
静态::
self::
之间有区别,就像在这个例子中(从)

产生

  • '一,静态::'=>'测试1'
  • 'two,static::'=>'test2'
  • 'one,self::'=>'test1'
  • 'two,self::'=>'test1'
  • '一,$this::'=>'测试1'
  • 'two,$this::'=>'test2'

因此self指的是定义方法的类,但在这些非静态方法中,
$this:
static::
之间没有区别。

实际上没有区别。
功能随着时间的推移而扩展,因此左侧不需要是类文字,也可以是具有类名的对象实例或字符串变量。大约在同一时间,使用
static
关键字引入了后期静态绑定。正如您所说,
$this
不能用于静态方法,因此
static
显然是后期静态绑定的唯一选择

但是,在对象实例中,您可以使用
static::
引用后期静态绑定类,该类将是当前对象实例的类。或者您可以使用
$this::
作为能够使用对象实例作为
的速记的副作用。最终的结果是一样的,只是功能在这一点上发生了重叠。内部工作原理有些不同,但我想不出会有什么不同

仅需完成维恩图:

只有
static
可以执行此操作:

public static function foo() {
    static::FOO;
}
$obj = new Foo;
$obj::FOO;
public function foo() {
    static::FOO;
    $this::FOO;
}
只有
$var::
可以执行此操作:

public static function foo() {
    static::FOO;
}
$obj = new Foo;
$obj::FOO;
public function foo() {
    static::FOO;
    $this::FOO;
}
两者都可以做到这一点:

public static function foo() {
    static::FOO;
}
$obj = new Foo;
$obj::FOO;
public function foo() {
    static::FOO;
    $this::FOO;
}

有三种情况下,无法使用
$this:
而不是
静态::

1。在静态方法中

public static function test() {
    return $this::MY_CONST;
}
输出:

致命错误:未捕获错误:不在对象上下文中时使用$this

2。在非对象上下文中调用的非静态方法中

class A {
    const MY_CONST = 33;
    public function test() {
        return $this::MY_CONST;
    }
}

echo A::test(); // test method here is called without instantiating class A
输出:

致命错误:未捕获错误:不在对象上下文中时使用$this

3。使用特殊的
::class
关键字时

class A {
    public function test() {
        return $this::class;
    }
}

$a = new A;
echo $a->test();
输出:

致命错误:编译时不允许使用动态类名

注意:在所有这三种情况下,
静态::
都将起作用


最后一个案子 声明:

注意:

使用::class的类名解析是编译时的 转型这意味着在类名字符串为 尚未创建自动加载。因此,类名 即使该类不存在,也会展开。中未发出任何错误 那个案子

因此您不能使用
$this::class
,因为您不能引用不存在的类

public static function test() {
    return $this::MY_CONST;
}
PHP 8 PHP8中的行为已经改变

出于一致性原因,
$this::class
现在提供与
get\u class($this)
static::class


你的最后一个结论确实是正确的:)我确实忘记了
$this::class
,这是一个很好的例子,因为其他方法实际上是基于静态方法的(或者“像静态方法一样调用”,即任何地方都不存在
$this