Self in PHP

Source: Internet
Author: User
Tags definition class definition constant manual keyword list

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 ();

Running this code found that ' hello ' is not output,
To take a closer look, we found that class A's Say Method $this->__contruct () is problematic to call Class A's constructor, which actually calls B
This is to use self
The meaning of this keyword modification is "static," which mentions self, parent, and static in the PHP manual, but in fact the other two are not keywords except the static keyword, and there are no two keywords in the manual keyword list, To verify this is simple:
Var_dump (self); -> string (4) "Self"
The code above does not give an error, and if you turn error_reporting (e_all) on, you can see what the actual situation is: Running this code will appear "Notice:use of undefined constant self-assumed ' self ' ", which means that PHP treats self as a normal constant, and an attempt to undefined constants treats the output itself as a string, such as" self "in the example above, but it also gives a notice, which means that the self identifier is nothing special.
Self is a special class that points to the current class, but only if it is valid inside a class definition and requires more than just within the definition of a class, but also in the context of a class, such as new self (), when self points to the current class.
So the say method of Class A is changed to Self::__parent ()



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.