Examples of constructor methods in php object-oriented programming

WBOY
Release: 2016-07-25 09:00:55
Original
919 people have browsed it
Let me introduce to you an example of the construction method of PHP object-oriented programming. Friends in need can refer to it.

Basic syntax for customizing constructors in classes: //php5 [Modifier]function __construct([parameter list]){ } //php4 [Modifier]function class name([parameter list]){ }

Learn programming, novices learn PHP object-oriented programming, look at more examples and practice more, and you will make rapid progress. No matter how good the PHP tutorial is, it can't teach you how to write code. You can only practice more on your own!

Let’s look at specific examples so that it’s easier to understand.

name=$name; $this->age=$age; } //构造方法 php4 写在这里是php5为了兼容PHP4 public function Person($name,$age){ $this->name=$name; $this->age=$age; } } $p1=new Person("老大",27); echo $p1->name; $p1=new Person("小二",26); $p1=new Person("小三",24); ?>
Copy after login

Note: 1), understanding of $this: 1. The essence of $this can be understood to be the address of this object. 2. Which object uses $this is the address of that object. 3. $this cannot be used outside the class 2) Understanding of construction methods: The constructor method name is the same as the class name (php4 version). The constructor method name of php5 version can be the same as the class name, or it can be __construct(). The default access modifier of the constructor is public, and the constructor has no return value. After successfully creating a new object, the system automatically calls the constructor of the class. A class has one and only one constructor. After PHP5, although __construct() and classname() can coexist, only one can actually be used. If there is no custom constructor for the class, the class uses the system default constructor. If a constructor is customized for a class, the default constructor of the class is overridden.

With the above learning, PHP object-oriented constructor is no longer difficult.



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