Methods automatically called by objects in PHP: set (), get (), tostring ()

Source: Internet
Author: User
Methods automatically called by objects in PHP: set (), get (), tostring () summary:

(1) _ get ($ property_name): When you get the value of $ name for a private attribute, this object automatically calls this method and passes the attribute name value to the parameter $ property_name, internal

Run the command to return the value of the private attribute we passed in.

(2) _ set ($ property_name, $ value): When a value is directly assigned to a private property, this object will automatically call this method and pass the property such as name to $ property_name, assign the value

"Zhangsan" is passed to $ value. this method is used for value assignment.

(3) _ tostring (): when a direct output handle (which can be understood as an instance), The _ tostring () method is automatically executed.

1. _ set () and _ get ().

In general, the class attribute is always defined as private, which is more in line with the actual logic. However, attributes are read and assigned frequently. Therefore, two functions are predefined in PHP5.

"_ Get ()" and "_ set ()" are used to obtain and assign values to their attributes, and to check the "_ isset ()" of the attributes () and the method "_ unset ()" for deleting an attribute ()".


We set and obtain each attribute. in PHP5, we provide a method specifically for setting and obtaining values for the attribute, "_ set () "and" _ get () "methods, which do not exist by default,

Instead, we manually add them to the class. just like the constructor (_ construct (), the two methods are added to the class. you can add them as follows, of course, you can also add it in your own style:

// _ Get () method is used to obtain the private property public function _ get ($ property_name) {if (isset ($ this-> $ property_name )) {return ($ this-> $ property_name);} else {return (NULL) ;}// _ set () set the private property public function _ set ($ property_name, $ value) {$ this-> $ property_name = $ value ;}

_ Get (): This method is used to obtain the attribute value of a private member. there is a parameter that is used to input the name of the member attribute you want to obtain and return the obtained attribute value, this method does not need to be manually called, because we can also make this method a private method, which is automatically called when the object directly obtains the private property. Because private attributes have been encapsulated, values cannot be obtained directly (for example, "echo $ p1-> name" is incorrect ), however, if you add this method to the class, when you use a statement such as "echo $ p1-> name" to directly obtain the value, it will automatically call _ get ($ property_name) to pass the attribute name to the parameter $ property_name. The value of the private attribute we passed in is returned through the internal execution of this method. If the member attributes 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. There are two parameters. The first parameter is the attribute name for the set value, the second parameter is the value to be set for the attribute, with no return value. This method does not need to be called manually. It can also be made private. it is automatically called when private property values are directly set. Similarly, the private property has been encapsulated.

The _ set () method is not allowed, for example, $ this-> name = 'hangsan, however, if you add the _ set ($ property_name, $ value) method to the class, it will be automatically called when the private property is assigned a value directly, pass the attribute such as name to $ property_name, and pass the value "zhangsan" to $ value. this method is used to assign values. If the member attributes are not encapsulated as private, the object itself will not automatically call this method. In order not to pass in invalid values, you can also make a judgment in this method. The code is as follows:

 "; If (isset ($ this-> $ property_name) {return ($ this-> $ property_name);} else {return (NULL );}} // _ set () is used to set the private property public function _ set ($ property_name, $ value) {echo "when setting the private property value directly, the _ set () method is automatically called to assign values to private attributes.
"; $ This-> $ property_name = $ value ;}$ per = new person (); $ per-> name =" shirayner "; // $ per automatically calls the _ set ($ property_name, $ value) method echo $ per-> name; // $ per automatically calls _ get ($ property_name) at this time) method?> 2. _ tostring () TOstring ). When testing, you need to know whether the data is correct. For example, when printing an object, you can check what attributes and values the object has. if the class defines the toString method, echo can print the object body during the test, the object automatically calls the toString method defined by the class to format and output the data contained in the object. If this method is not available, an error will be returned for echo an Object. for example, the syntax "Catchable fatal error: Object of class Account cocould not be converted tostring" is incorrect. In fact, this is a type matching failure error. However, you can still use the print_r () and var_dump () functions to output an object. Of course, toString can be customized and provides more information and styles.
    
class Account{
public $user=1;
private $pwd=2;
// Customize the formatting output method
public function toString(){
Return "the username of the current object is {$ this-> user}, and the password is {$ this-> pwd }";
}
}
$a=new Account();
echo $a;
echo PHP_EOL;
print_r($a);

After running this code, we can find that the output result is customizable and easier to understand after the toString method is used. In fact, the design prototype of the toString magic method of PHP comes from Java. There is also such a method in Java, and this method is widely used in Java, which is more convenient for debugging programs. In fact, the toString method is also a serialization method. we know that the built-in serialize/unserialize in PHP is also serialized, but this function will generate some useless information, such as the attribute string length, this may cause unnecessary waste of storage space. Therefore, you can implement your own serialization and deserialization methods, or json_encode/json_decode is also a good choice.

Why does a syntax error occur when an object is directly echo? if this object implements the toString method, it can be directly output? The reason is very simple. echo can print an object and implement this interface. However, PHP imposes a limit on it and can only be used after toString is implemented. The following PHP source code can be used for verification:

ZEND_VM_HANDLER(40, ZEND_ECHO, CONST|TMP|VAR|CV, ANY)
{
zend_op *opline = EX(opline);
zend_free_op free_op1;
zval z_copy;
zval *z = GET_OP1_ZVAL_PTR(BP_VAR_R);
// The code here reserves the interface for converting objects into strings
if (OP1_TYPE != IS_CONST &&
Z_TYPE_P(z) == IS_OBJECT && Z_OBJ_HT_P(z)->get_method != NULL &&
zend_std_cast_object_tostring(z, &z_copy, IS_STRING TSRMLS_CC) == SUCCESS) {
zend_print_variable(&z_copy);
zval_dtor(&z_copy);
} else {
zend_print_variable(z);
}
 
FREE_OP1();
ZEND_VM_NEXT_OPCODE();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.