static 针对的是正在使用中的类,self 针对的是此时代码所在的类
<?php
class Test
{
const NAME = 1;
public function getName()
{
echo static::NAME;
}
}
class Person extends Test{
const NAME = 22;
}
$per = new Person();
$per->getName(); //22
//如果 getName echo self::NAME; 则打印出 11
- static() 打印出来的是类
<?php
class DomainObject
{
public static function create()
{
return new static();
}
}
class User extends DomainObject
{
}
var_dump(User::create());
![](https://img.haomeiwen.com/i2560633/4dd612f100f7d72f.png)
- self 是父类
<?php
class DomainObject
{
public static function create()
{
return new self();
}
}
class User extends DomainObject
{
}
var_dump(User::create());
![](https://img.haomeiwen.com/i2560633/05574887d08167d0.png)
-
但是,如果 DomainObject 是抽象类,只能用 static 不能用 self,因为抽象类是不可以实例化的
-
正确写法
<?php
abstract class DomainObject
{
public static function create()
{
return new static();
}
}
class User extends DomainObject
{
}
var_dump(User::create());
- 错误写法
public static function create()
{
return new self();
}
![](https://img.haomeiwen.com/i2560633/a28379138fa08e01.png)
self 指的并不是调用上下文,它指的是解析上下文。此处指 DomainObject
static 类似于 self,但他指的是被调用的类,而不是包含的类。此处它指 User
上面的例子,并不是因为使用了静态方法,即使使用非静态方法,也是这个结果
- 正确
<?php
abstract class DomainObject
{
public function create()
{
return new static();
}
}
class User extends DomainObject
{
}
$user = new User();
var_dump($user->create());
![](https://img.haomeiwen.com/i2560633/cc1c5f62a8186e1b.png)
- 错误
<?php
abstract class DomainObject
{
public function create()
{
return new self();
}
}
class User extends DomainObject
{
}
$user = new User();
var_dump($user->create());
![](https://img.haomeiwen.com/i2560633/8ad91d233aa34a04.png)
网友评论