美文网首页
php 类中 static 与 self 的区别

php 类中 static 与 self 的区别

作者: 云龙789 | 来源:发表于2019-03-11 23:46 被阅读0次

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());
static.png
  • self 是父类
<?php

class DomainObject
{
    public static function create()
    {
        return new self();
    }
}

class User extends DomainObject
{

}
var_dump(User::create());
self
  • 但是,如果 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();
    }
return new self(); 的报错

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());
图片.png
  • 错误
<?php

abstract class DomainObject
{
    public function create()
    {
        return new self();
    }
}

class User extends DomainObject
{

}

$user = new User();
var_dump($user->create());
图片.png

相关文章

网友评论

      本文标题:php 类中 static 与 self 的区别

      本文链接:https://www.haomeiwen.com/subject/lwlwpqtx.html