PHP5.3之后的static到底怎么了? 有实例代码哦,非标题党

WBOY
Release: 2016-06-06 20:48:11
Original
1012 people have browsed it

1: 成功

<code class="lang-php"><?php abstract class DomainObject
{
    public  static function create()
    {
        return new static();
    }
}

class User extends DomainObject
{

}

class Document extends DomainObject
{

}

Document::create();
</code></code>
Copy after login
Copy after login

2: 失败

<code class="lang-php"><?php abstract class DomainObject
{
    public  static function create()
    {
        return new self();
    }
}

class User extends DomainObject
{

}

class Document extends DomainObject
{

}

Document::create();
</code></code>
Copy after login
Copy after login

我就想知道如何正确理解static,如何适度的使用static?

回复内容:

1: 成功

<code class="lang-php"><?php abstract class DomainObject
{
    public  static function create()
    {
        return new static();
    }
}

class User extends DomainObject
{

}

class Document extends DomainObject
{

}

Document::create();
</code></code>
Copy after login
Copy after login

2: 失败

<code class="lang-php"><?php abstract class DomainObject
{
    public  static function create()
    {
        return new self();
    }
}

class User extends DomainObject
{

}

class Document extends DomainObject
{

}

Document::create();
</code></code>
Copy after login
Copy after login

我就想知道如何正确理解static,如何适度的使用static?

PHP 5.3 之后,实现了延迟绑定。http://www.php-internals.com/book/?p=chapt05/05-05-class-magic-methods-latebinding

在之前的版本中,如果运行下面的代码:

<code class="lang-php"><?php abstract class DomainObject
{
    public  static function create()
    {
        return new self();
    }
}

class User extends DomainObject
{

}

class Document extends DomainObject
{

}

$foo = Document::create();
</code></code>
Copy after login

那么 $foo 得到的是一个 Domain 对象而不是 Document 的对象,这是由于之前的 PHP 版本中存在的一个问题,就是父类无法获得子类的状态,导致在继承时 self 这个值指向的是父类而非子类。如果要实现正常的功能的话,必须在子类中重写方法。

后来在 PHP 5.3 中,引入了 static 来实现延迟绑定,只需要用 static 来替换 self 关键字即可。

很容易理解啊,self就是当前类或者当前类的父类,那么楼主的例子中,去实例化一个抽象类,这肯定是错误的。而static官方解释是静态晚绑定的意思,通俗点就是一个子类,那么这样子的话楼主的例子必然可以走通啊。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!