Home > php教程 > php手册 > body text

活用php的self

WBOY
Release: 2016-06-21 08:52:04
Original
814 people have browsed it

class A{
private $handle;
public funciton __construct(){
}
public function say($word){
if(!isset($handle)){
$this->__construct();
}
echo $word;
}
}
class B extends A{
private $word;
public funciton __construct($word){
$this->word = $word;
}
pulbi function call(){
$this->say($this->word);
}
}
$b = new B('hello');
$b->call();

运行这段代码发现不会输出 ‘hello’,
仔细看看,发现class A的say方法中 $this->__contruct()很有问题,本来是想调用class A的构造函数,实际上调用了B
这是得使用 self
这个关键字修饰的意义都表示"静态",在PHP手册中提到self, parent和static这几个关键字,但实际上除了static是关键字以外,其他两个均不是关键字,在手册的关键字列表中也没有这两个关键字,要验证这一点很简单:
var_dump(self); // -> string(4) "self"
上面的代码并没有报错,如果你把error_reporting(E_ALL)打开,就能看到实际是什么情况了:运行这段代码会出现“ Notice: Use of undefined constant self - assumed 'self'“,也就是说PHP把self当成一个普通常量了,尝试未定义的常量会把产量本身当成一个字符串,例如上例的”self",不过同时会出一个NOTICE,这就是说self这个标示符并没有什么特殊的。
self是一个特殊类,它指向当前类,但只有在类定义内部才有效,它不止要求在类的定义内部,还要求在类的上下文环境,比如 new self()的时候,这时self就指向当前类。
因此class A的say方法 改为 self::__parent()即可



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 Recommendations
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!