Home Backend Development PHP Tutorial A few notes on the improved object-oriented approach to PHP Page 1/2_PHP Tutorial

A few notes on the improved object-oriented approach to PHP Page 1/2_PHP Tutorial

Jul 21, 2016 pm 03:48 PM
class php code copy 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: Can't read a property other than x & yn";
}
}
function __set($property, $value)
{
if (array_key_exists($property, $this->arr)) {
$this->arr[$property] = $value;
} else {
print "Error: Can't write a property other than x & yn";
}
}
}
$obj = new StrictCoordinateClass();
$obj->x = 1;
print $obj->x;
print "
";
$obj->n = 2;
print "
";
print $obj->n;
?>

Output result:
StrictCoordinateClass is being created
1
Error: Can't write a property other than x & y
Error: Can't read a property other than x & y
StrictCoordinateClass is being destroyed
__construct() and __destruct() are equivalent to the constructor in Java and the destructor in C.
As for __get and __set, please see below:
Reference from: http://www.phpchina.com/html/54/26354-31906.html
.__set() __get() __isset( ) Application of the four methods of __unset()
Generally speaking, always define the attributes of a class as private, which is more in line with realistic logic. However, reading and assigning operations to attributes are very frequent, so in PHP5, two functions "__get()" and "__set()" are predefined to obtain and assign their attributes, as well as "__isset" to check the attributes. ()" and the method to delete attributes "__unset()".
In the previous section, we set and obtained methods for each attribute. PHP5 provides us with special methods for setting and obtaining values ​​for attributes, "__set()" and "__get()" These two methods, these two methods do not exist by default, but we add them to the class manually. Like the constructor method (__construct()), it will only exist if it is added to the class. You can add it in the following way Of course, these two methods can also be added according to personal style:
//__get() method is used to obtain 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;
}
__get() method: This method is used to get the private member attribute value. It has one parameter. The parameter is passed in the name of the member attribute you want to get, and the obtained attribute value is returned. This method does not need to be called manually, because We can also make this method a private method, which is automatically called by the object when the private property is directly obtained. Because the private properties have been encapsulated, the value cannot be obtained directly (for example: "echo $p1->name" is wrong to obtain directly), but if you add this method to the class, use " When a statement like "echo $p1->name" directly obtains the value, the __get($property_name) method will be automatically called, and the property name will be passed to the parameter $property_name. Through the internal execution of this method, the private value we passed in will be returned. The value of the attribute. If the member properties are not encapsulated as private, the object itself will not automatically call this method.
__set() method: This method is used to set values ​​for private member attributes. It has two parameters. The first parameter is the name of the attribute you want to set the value for, and the second parameter is the value you want to set for the attribute. , no return value. This method also does not need to be called manually. It can also be made private. It is automatically called when directly setting the private attribute value. The same private attribute has been encapsulated with
. If there is no __set() Methods are not allowed, for example: $this->name='zhangsan', this will cause an error, but if you add the __set($property_name, $value) method to the class, you can directly set the private property When assigning a value, it will be automatically called, passing the attribute such as name to $property_name, and passing the value "zhangsan" to be assigned to $value. Through the execution of this method, the purpose of assignment is achieved. If the member properties are not encapsulated as private, the object itself will not automatically call this method. In order not to pass in illegal values, you can also make a judgment in this method. The code is as follows:
classPerson
{
//The following are the member attributes of the person, which are all encapsulated private members
private $name; //The person’s name
private $sex; //Person’s gender
private $age; //Person’s age
//__get() method is used to obtain private properties
private function__get($property_name)
{
echo"When directly obtaining the private property value, this __get() method is automatically called
";
if(isset($this->$property_name))
{
return($this->$property_name);
}
else
{
return(NULL);
}
}
//__set() method Used to set private properties
private function__set($property_name,$value)
{
echo" When directly setting the value of a private property, this __set() method is automatically called to assign a value to the private property< br>";
$this->$property_name=$value;
}
}
$p1=newPerson();
//The operation of directly assigning a value to a private property will Automatically call the __set() method to assign values ​​
$p1->name="Zhang San";
$p1->sex="Male";
$p1->age=20;
//Get the value of the private attribute directly, the __get() method will be automatically called to return the value of the member attribute
echo "Name:".$p1->name."
";
echo"Gender:".$p1->sex."
";
echo"Age:".$p1->age."
";
?> ;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/319639.htmlTechArticleLook at the code first: Copy the code as follows: ?php class StrictCoordinateClass { private $arr = array('x' = NULL, 'y' = NULL); function __construct() { print "StrictCoordinateClass is...
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 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1670
14
PHP Tutorial
1274
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