Home Backend Development PHP Tutorial A little explanation of the improved object-oriented PHP_PHP tutorial

A little explanation of the improved object-oriented PHP_PHP tutorial

Jul 13, 2016 pm 05:35 PM
class php code object Improve illustrate For

先看代码:
class StrictCoordinateClass {
private $arr = array(x => NULL, y => NULL);
function __construct() {
print "StrictCoordinateClass is being created";
print "
";
}
function __destruct() {
print "
";
print "StrictCoordinateClass is being destroyed";
}
function __get($property) {
if (array_key_exists($property, $this->arr)) {
return $this->arr[$property];
} else {
print "Error: Cant read a property other than x & y ";
}
}
function __set($property, $value) {
if (array_key_exists($property, $this->arr)) {
$this->arr[$property] = $value;
} else {
print "Error: Cant write a property other than x & y ";
}
}
}
$obj = new StrictCoordinateClass();
$obj->x = 1;
print $obj->x;
print "
";
$obj->n = 2;
print "
";
print $obj->n;
?>

输出结果:
StrictCoordinateClass is being created
1
Error: Cant write a property other than x & y
Error: Cant read a property other than x & y
StrictCoordinateClass is being destroyed
__construct()和__destruct()相当于Java中的构造函数以及C中的析构函数。
至于__get和__set请看下文:
参考自:http://www.phpchina.com/html/54/26354-31906.html
.__set() __get() __isset() __unset()四个方法的应用
一般来说,总是把类的属性定义为private,这更符合现实的逻辑。但是,对属性的读取和赋值操作是非常频繁的,因此在PHP5中,预定义了两个函数“__get()”和“__set()”来获取和赋值其属性,以及检查属性的“__isset()”和删除属性的方法“__unset()”。
上一节中,我们为每个属性做了设置和获取的方法,在PHP5中给我们提供了专门为属性设置值和获取值的方法,“__set()”和“__get()”这两个方法,这两个方法不是默认存在的,而是我们手工添加到类里面去的,像构造方法(__construct())一样,类里面添加了才会存在,可以按下面的方式来添加这两个方法,当然也可以按个人的风格来添加:
//__get()方法用来获取私有属性
private function__get($property_name) {
if(isset($this->$property_name)) {
return($this->$property_name);
}else {
return(NULL);
}
}
//__set()方法用来设置私有属性
private function__set($property_name,$value) {
$this->$property_name=$value;
}
__get() 方法:这个方法用来获取私有成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值,这个方法不用我们手工的去调用,因为我们也可以把这个方法做成私有的方法,是在直接获取私有属性的时候对象自动调用的。因为私有属性已经被封装上了,是不能直接获取值的(比如:“echo $p1->name”这样直接获取是错误的),但是如果你在类里面加上了这个方法,在使用“echo $p1->name”这样的语句直接获取值的时候就会自动调用__get($property_name)方法,将属性name传给参数$property_name,通过这个方法的内部执行,返回我们传入的私有属性的值。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。
__set() 方法:这个方法用来为私有成员属性设置值的,有两个参数,第一个参数为你要为设置值的属性名,第二个参数是要给属性设置的值,没有返回值。这个方法同样不用我们手工去调用,它也可以做成私有的,是在直接设置私有属性值的时候自动调用的,同样属性私有的已经被封装上
了,如果没有__set()这个方法,是不允许的,比如:$this->name=‘zhangsan,这样会出错,但是如果你在类里面加上了 __set($property_name, $value)这个方法,在直接给私有属性赋值的时候,就会自动调用它,把属性比如name传给$property_name,把要赋的值 “zhangsan”传给$value,通过这个方法的执行,达到赋值的目的。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。为了不传入非法的值,还可以在这个方法给做一下判断。代码如下:
classPerson {
//下面是人的成员属性, 都是封装的私有成员
private $name; //人的名子
private $sex; //人的性别
private $age; //人的年龄
//__get()方法用来获取私有属性
private function__get($property_name) {
echo"在直接获取私有属性值的时候,自动调用了这个__get()方法
";
if(isset($this->$property_name)) {
return($this->$property_name);
} else {
return(NULL);
}
}
//__set()方法用来设置私有属性
private function__set($property_name,$value) {
echo"在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
";
$this->$property_name=$value;
}
}
$p1=newPerson();
//直接为私有属性赋值的操作, 会自动调用__set()方法进行赋值
$p1->name="张三";
$p1->sex="男";
$p1->age=20;
//直接获取私有属性的值, 会自动调用__get()方法,返回成员属性的值
echo"姓名:".$p1->name."
";
echo"性别:".$p1->sex."
";
echo"年龄:".$p1->age."
";
?>

Program execution results:
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
When directly setting the value of a private attribute, this __set is automatically called. The () method assigns values ​​to private attributes
When directly setting the value of a private attribute, the __set() method automatically calls the __set() method to assign a value to a private attribute
When directly obtaining the value of a private attribute, the __get is automatically called () method
Name: Zhang San
When directly obtaining the private attribute value, the __get() method is automatically called
Gender: Male
When directly obtaining the private attribute value, the __get() method is automatically called This __get() method is called
Age: 20
If the above code does not add the __get() and __set() methods, the program will go wrong, because private members cannot be operated outside the class, and The above code helps us directly access the encapsulated private members by automatically calling the __get() and __set() methods.
__isset() method: Before looking at this method, let’s take a look at the application of the “isset()” function. isset() is a function used to determine whether a variable is set. Pass in a variable as a parameter. If the passed-in variable Returns true if it exists, otherwise returns false. So if you use the "isset()" function outside an object to determine whether the members inside the object are set, can you use it? There are two situations. If the members in the object are public, we can use this function to measure the member attributes. If they are private member attributes, this function will not work. The reason is that the private ones are encapsulated and are not exposed externally. Invisible. So we can't use the "isset()" function outside the object to determine whether the private member attributes have been set? Yes, you just need to add a "__isset()" method to the class. When the "isset()" function is used outside the class to determine whether the private members in the object are set, it will be automatically called inside the class. The "__isset()" method helps us complete such operations, and the "__isset()" method can also be made private. You can just add the following code to the class:
private function__isset($nm) {
echo"When the isset() function is used outside the class to determine the private member $nm, it is automatically called< br>";
return isset($this->$nm);
}
__unset() method: Before looking at this method, let’s first take a look at the "unset()" function , the function of "unset()" is to delete the specified variable and return true, and the parameter is the variable to be deleted. So if you want to delete the member attributes inside the object outside an object, can you use the "unset()" function? There are two situations. If the member attributes inside an object are public, you can use this function to delete them outside the object. The public attributes of the object. If the member attributes of the object are private, I will not have the permission to delete them using this function. But similarly, if you add the "__unset()" method to an object, you can delete it from outside the object. Private member properties of the object. After adding the "__unset()" method to the object, when using the "unset()" function outside the object to delete the private member attributes inside the object, the "__unset()" function is automatically called to help us delete the object. Internal private member attribute, this method can also be defined as private inside the class. Just add the following code to the object:
private function__unset($nm) {
echo "Automatically called when the unset() function is used outside the class to delete a private member
";
unset($this->$nm);
}
Let’s take a look at a complete example:
classPerson {
//The following is human Member attributes
private $name; //The person’s name
private $sex; //The person’s gender
private $age; //The person’s age
//__get() method is used Get private properties
private function__get($property_name) {
if(isset($this->$property_name)) {
return($this->$property_name);
}else{
return(NULL);
}
}
//__set() method is used to set private properties
private function__set($property_name,$value) {
$this-> ;$property_name=$value;
}
//__isset() method
private function__isset($nm) {
When the echo "isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function__unset($nm) {
echo" when used outside the class The unset() function is automatically called when deleting private members
";
unset($this->$nm);
}
}
$p1=newPerson();
$p1->name="this is a person name";
//When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echovar_dump(isset($p1->name))."
";
echo $p1->name."
";

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/508329.htmlTechArticle先看代码: ?php class StrictCoordinateClass { private $arr = array(x = NULL, y = NULL); function __construct() { print "StrictCoordinateClass is being created"; print "br/"; }...

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles