Home Backend Development PHP Tutorial Learn PHP while memorizing-(12) Object-oriented programming 2

Learn PHP while memorizing-(12) Object-oriented programming 2

Aug 08, 2016 am 09:32 AM
gt public quot school this

There is a bit of time between this article and the previous one, and a small project was inserted in the middle. But it doesn't matter, "Learning PHP while Memorizing" will continue.

PHP Object-Oriented Programming

(2) Class attributes

The so-called class attributes are variables declared in the class. The difference between it and variables declared outside the class is that the modified permissions are added in front, which is the public/private/protected in the previous article. For example, I want to declare a student class, which contains the student's student number, name, gender, age, class, etc. Then I can declare as follows:

<?php
class Student{
	private $sid;
	private $name;
	private $gender;
	private $age;
	private $grade;

	public getSid(){
		return $this->sid;
	}
	public getName(){
		return $this->name;
	}
	public getGender(){
		return $this->gender;
	}
	public getAge(){
		return $this->age;
	}
	public getGrade(){
		return $this->grade;
	}

	public setSid($sid){
		$this->sid = $sid;
	}
	public setName($name){
		$this->name = $name;
	}
	public setGender($gender){
		$this->gender = $gender;
	}
	public setAge($age){
		$this->age = $age;
	}
	public setGrade($grade){
		$this->grade = $grade;
	}

}
Copy after login

In the student class above, I declared five attributes, all of which are declared private. Then they cannot be accessed directly outside the class, so I Two methods are provided for each of their properties, to access them and to set their values. Generally, when declaring a class, the properties are declared as private and the member methods are declared as public, then the outside world can access the private properties through the public methods. And when declaring access and setting methods, the form getXXX() and setXXX() are generally used. The first letter of XXX is usually capitalized. Of course, they can also be declared as public properties, so they can be assigned values ​​directly and accessed outside the class. However, it is still recommended to declare it as a private attribute, because if it is standardized in the future, each class will live as a separate PHP file to specifically store this class. Declaring it as private will ensure that the values ​​​​in the objects of this class will not be changed at will, ensuring security.

When declaring attributes, you can also assign values ​​while declaring them, just like extra-class variables.

Note here:

Attributes can store a value, an array, or even an object of another class. For example, add school attributes to the student class above. This school is also a class, including the school's name, address, etc. I first declare the school class

class School{
	private $name;
	private $address;

	public getName(){
		return $this->name;
	}
	public getAddress(){
		return $this->address;
	}
	public setName($name){
		$this->name = $name;
	}
	public setAddress($address){
		$this->address = $address;
	}
}
Copy after login
Then I can add the school attribute to the student class like this:

<?php
class Student{
	...
	private $school;

	...
	public getSchool(){
		return $this->school;
	}

	...
	public setSchool($school){
		$this->school = $school;
	}

}
Copy after login
This way looks the same as other attributes, but when assigning it to When taking the parameter, please note that the object is passed. For example:

I first declare a school:

<span style="white-space:pre">	</span>$school1 = new School();
<span style="white-space:pre">	</span>$school1->setName("大连理工大学");
<span style="white-space:pre">	</span>$school1->setAddress("大连");
<span style="white-space:pre">	</span>$stu1 = new Student();
<span style="white-space:pre">	</span>$stu1->setSchool($school1);
Copy after login
In this way becomes an object when visiting its school. If I want to know the name of the school where this student is, I will To access it like this:

<span style="white-space:pre">	</span>$stu1->getSchool()->getName();
Copy after login
Use the getSchool method to get a School object, then use the getName method in the School object to access its name.

                                                                                                used to use the $this keyword when accessing variables in the class, so let’s talk about the this keyword.

(3) $this keyword

Whether it is declared as a public, private or protected member variable, there will definitely be access to your own variables in the class, then you must use the $this key Character. In my opinion, the $this keyword refers to the class itself. I can also understand it as treating itself as an object to call its own properties. Note here that we use the $ symbol when declaring the variable, but if we use $this to access, only this plus the $ symbol, do not add the subsequent attributes, otherwise an error will be reported. For specific usage, refer to the code above. Of course, if the object declared externally is called, it is the same as $this, and the $ symbol must be added to the object, but not later.

(4) Static attributes

I didn’t think of how to explain static attributes, but I saw this sentence in the book that says it very well: Static attributes are often used to represent a specific A persistent value that depends on the class and not on the instance object. We can think of static properties as tired global variables. An important feature of static properties is that when accessing static properties, there is no need to create an instance of the class, that is, there is no need to define an object of the class.

In the book, there is a static attribute of the sales quantity in the car category. In other words, no matter who buys the car, if it is sold anyway, then my sales quantity will be increased by 1. But I have already given the example of students and schools above. I will continue my example and say that I think of this attribute of a school graduate. That is to say, no matter who you are, as long as you graduate from my school, then I There will be 1 more school graduates. Then I can declare it like this:

<span style="white-space:pre">	</span>public static $graduate;
Copy after login
That is, add the static keyword in front of the variable. Then when I access this static attribute, I don’t need to use an object to access it. I use this class to access it directly, School::$graduate = ...; and that’s it. This is what is said above that objects that do not need to be defined can be accessed. Here I can use a picture to illustrate the difference between static attributes and ordinary attributes:

静态属性只占这个内存,不管存不存在对象实例,除非这个类没了,否则会一直占有自己的内存。而普通的属性在每次声明对象的时候都会分配内存。

静态属性一般声明成公有的。

(6)类常量

与类外的普通常量一样,类常量也是存储一个固定的值。使用const关键字进行声明,这里不需要加权限修饰。在访问的时候跟访问静态属性一样需要使用类名::(双冒号)加常量名来访问。比如如果我声明一个手机类,手机有各种型号,那么我可以把各个手机型号用常量来存储,在给手机型号属性赋值的时候使用这些常量来赋值就好了。但是可能有这种疑惑,为什么要使用常量,我直接声明不就行了。那么可以这样理解:

class Phone{
	const IPHONE = 1;
	const ZTE = 2;
	const HUAWEI = 3;

    //这里面各种属性

}
Copy after login
我这个是一个手机类,里面声明了三个常量,这里注意,声明常量不需要$符号,并且常量的名字一般大写。但是你注意我在里面存储的是int型的数据,如果我给手机型号赋值的时候虽然给他赋值是类似:$this->type = ZTE;但是我的型号存的是int型的数据,那么就会占内存少,如果我不适用常量$this->type = 'ZTE';这样我就存的字符串。并且使用常量可以提高编译速度。

这是我理解的常量的优点。但是我没怎么用过。

下一篇继续面向对象。

以上就介绍了边记边学PHP-(十二)面向对象编程2,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

What is the difference between the developer version and the public version of iOS? What is the difference between the developer version and the public version of iOS? Mar 01, 2024 pm 12:55 PM

Every year before Apple releases a new major version of iOS and macOS, users can download the beta version several months in advance and experience it first. Since the software is used by both the public and developers, Apple has launched developer and public versions, which are public beta versions of the developer beta version, for both. What is the difference between the developer version and the public version of iOS? Literally speaking, the developer version is a developer test version, and the public version is a public test version. The developer version and the public version target different audiences. The developer version is used by Apple for testing by developers. You need an Apple developer account to download and upgrade it.

Deal | Affordable HP Victus gaming laptop with RTX 3050-beating RX 6550M gets 40% discount in Best Buy sale Deal | Affordable HP Victus gaming laptop with RTX 3050-beating RX 6550M gets 40% discount in Best Buy sale Aug 09, 2024 pm 09:51 PM

The HP Victus 15 is 1 15.6-inch entry-level gaming laptop that ordinarily wouldn't be worth much consideration, however a new Best Buy deal offers 40% off the entry-level gaming laptop, bringing the price down from $799.99 to a very budget-friendly $

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

An article that understands this point and catches up with 70% of front-end people An article that understands this point and catches up with 70% of front-end people Sep 06, 2022 pm 05:03 PM

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

See all articles