Home  >  Article  >  Backend Development  >  [FAQ] Some common sense in PHP: Classes_PHP Tutorial

[FAQ] Some common sense in PHP: Classes_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 16:10:07938browse


I have sorted out some common sense about PHP classes to make it easier for novices to master PHP classes so that they can quickly understand the programs written by the bosses. Haha, there are relatively few. I hope the bosses can add to them or correct their misunderstandings.

Q: Can classes in PHP have constructors?
A: Yes, as long as the function name and class name are the same, this function will become a constructor. When using the new operator to create an instance of a class, the constructor will be automatically called, so some initialization work can be done in the constructor.

Q: Do classes in PHP have destructors?
A: No. When the object is destroyed, using unset() or simply going out of scope, the destructor is automatically called. But there is no destructor in PHP. For example:
unset($foo);
destroys a class object $foo.


Q: How to inherit a class?
A: Use the keyword extends to inherit a class, such as:
class B extents A {
}


Q: How to reference itself in the definition of a class?
A: Use $this to refer to the current class itself, such as:
$this->name = "Tom";


Q: How to use the parent class in a subclass?
A: Use the :: operator, and there are two ways. One is to use the parent class name directly, such as:
A::example();
The other is to use the parent keyword, such as :
parent::example();
It is recommended to use parent:: to reference the parent class.


Q: I don’t want to create an instance of a class. Can I use the functions or variables in the class directly?
A: Yes, you can use the :: operator, such as:
B::example();
to execute the function example() in class B without creating any objects of class B. It is only called as a class function, which is very good for the inductive organization of function modules.


Q: Does PHP have multiple inheritance? //added by erquan
A: No. Subclasses cannot inherit from two parent classes at the same time, that is, a child cannot have two dads at the same time :). A subclass must depend on a base class that must already exist.​

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314338.htmlTechArticleI have compiled some common sense about PHP classes to make it easier for novices to master PHP classes so that they can quickly Understand the programs written by the bosses, haha, but there are relatively few. I hope the bosses can add more...
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