Explanation of the self keyword in PHP programming_PHP tutorial

WBOY
Release: 2016-07-21 14:56:29
Original
940 people have browsed it

 Bkjia.Com Programming Document self generally points to the static methods and constants of the current class, and is referenced using self:: plus method names and constant names. $this points to the instance object of the current class, which is referenced using $this-> plus method name and instance variable. In some methods whose parameters are callback, you can use the string 'self' to point to the current class instead of using self directly, such as call_user_func('self', $method).

In addition, self always refers to the methods and constants of the current class. The subclass calls the static method of the parent class. The self in the parent class method still points to the parent class itself. If the method of the same name of the subclass overrides the parent class, Class method, you can use parent:: to refer to the parent class method.

以下为引用的内容:
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()));
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364235.htmlTechArticleLieHuo.Net programming document self generally points to the static methods and constants of the current class, using self: :Add method name and constant name to reference. $this points to the instance of the current class...
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