Home >php教程 >php手册 >php编程中关于self关键字的说明

php编程中关于self关键字的说明

WBOY
WBOYOriginal
2016-06-13 11:38:49926browse

  烈火建站学院(Bkjia.Com)编程文档 self一般指向当前类的静态方法和常量,用self::加方法名和常量名方式引用。$this则是指向当前类的实例对象,用$this->加方法名和实例变量方式引用。在一些参数为callback的方法里,可以用字符串'self'形式指向当前类,而不要直接用self,如call_user_func('self', $method)中。

  另外self引用的总是当前类的方法和常量,子类调用父类的静态方法,其中的父类方法中的self仍是指向父类本身的,如果子类的同名方法覆盖了父类方法,则可以用parent::来引用父类方法。

以下为引用的内容:
interface AppConstants {
const FOOBAR = 'Hello, World.';
}

class Example implements AppConstants {
public function test() {
echo self :: FOOBAR;
}
}

$obj = new Example();
$obj->test(); // outputs "Hello, world."

class MyClass {
const NAME = 'Foo';

protected function myFunc() {
echo "MyClass::myFunc()\n";
}
static public function display() {
echo self :: NAME;
}
static public function getInstance() {
$instance = new self;
return $instance;
}
}

class ChildClass extends MyClass {
const NAME = 'Child';

// Override parent's definition
public function myFunc() {
// But still call the parent function
parent :: myFunc();
echo "ChildClass::myFunc()\n";
}
}

$class = new ChildClass();
$class->myFunc();


echo('Class constant: ');
ChildClass :: display();
echo('Object class: ');
echo(get_class(ChildClass :: getInstance()));
?>
Statement:
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