Methods for automatic invocation of objects in PHP: Set (), Get (), ToString ()

Source: Internet
Author: User
Tags php source code
Summarize:

(1) __get ($property _name): When a private property $name value is obtained, this object automatically calls the method, passing the property name value to the parameter $property_name, through which the internal

Executes, returns the value of the private property that we passed in.

(2) __set ($property _name, $value): When assigning a value directly to a private property, this object automatically calls the method, passing the attribute such as name to $property_name, and assigning the value

"Zhangsan" to $value, through the execution of this method, to achieve the purpose of assignment.

(3) __tostring (): When the direct output handle (which can be understood as an instance), the __tostring () method is executed automatically.

1.__set () and __get ().

In general, it is more realistic logic to always define the properties of a class as private. However, read and assign operations to properties are very frequent, so in PHP5, two functions are predefined

"__get ()" and "__set ()" To get and assign their properties, as well as to check the properties of the "__isset ()" and delete the properties of the Method "__unset ()".


We have set up and acquired methods for each property, and in PHP5 we have provided a way to set values and get values specifically for the property, "__set ()" and "__get ()", two methods that are not by default,

But we add to the class by hand, like the construction Method (__construct ()), the class is added to exist, you can add the two methods as follows, of course, can also be added according to personal style:

The __get () method is used to get the private property public function __get ($property _name) {  if (isset ($this-$property _name)) {return ($this- > $property _name); }else{return (NULL);}} The __set () method is used to set the private property public function __set ($property _name, $value) {$this, $property _name = $value;}

__get () Method: This method is used to obtain the value of the private member property, there is a parameter, the parameter passed in the name of the member property you want to get, return the obtained property value, this method does not have to be called by us manually, because we can also make this method private method, the object is to get the private property directly Automatically called. Because the private property is already encapsulated, it is not possible to get the value directly (for example: "Echo $p 1->name"), but if you add this method to the class, use "Echo $p 1->name" When such a statement gets the value directly, it automatically calls the __get ($property _name) method, passes the property name to the parameter $property_name, and returns the value of our incoming private property through the internal execution of the method. If the member property is not encapsulated as private, the object itself does not automatically call this method.


__set () Method: This method is used to set the value of the private member property, there are two parameters, the first parameter is you want to set the value of the property name, the second parameter is to set the value of the property, there is no return value. This method does not have to be called manually, it can also be made private, is directly set the value of the private property is automatically invoked, the same property private has been encapsulated

, if there is no __set () This method is not allowed, such as: $this->name= ' Zhangsan ', this will be wrong, but if you add __set in the Class ($property _name, $value) This method, When assigning a value directly to a private property, it is automatically invoked, passing the attribute, such as name, to the $property_name, passing the value "Zhangsan" to the $value, which is executed to achieve the purpose of the assignment. If the member property is not encapsulated as private, the object itself does 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:

 ";  if (Isset ($this, $property _name)) {return ($this, $property _name);} else {return (NULL);}} The __set () method is used to set the private property of public function __set ($property _name, $value) {echo "Automatically calls this __set () method to assign a value to a private property when the value of the private property is set directly
"; $this $property _name = $value; }} $per =new person (); $per->name= "Shirayner"; At this point $per automatically calls __set ($property _name, $value) method Echo $per->name; At this point $per automatically calls the __get ($property _name) method? >2.__tostring () ToString (intentionally written here is to show that the method in PHP is not case-sensitive, but the actual development also needs to pay attention to the specification). When testing, you need to know if the correct data is being drawn. For example, when printing an object, look at the properties of this object, what the value is, if the class defines the ToString method, in the test, echo prints the object body, the object will automatically call its own class definition of the ToString method, formatted output this object contains data. If this is not the case, then the Echo object will be an error, such as "Catchable fatal Error:object of class account could not being converted ToString" syntax error, This is actually a type-matching failure error. However, you can still use the Print_r () and Var_dump () functions to output an object. Of course, ToString is customizable and offers a richer range of information and styles.
    
Class account{
public $user = 1;
Private $pwd = 2;
Custom formatted Output method
Public Function toString () {
Return "The user name of the current object is {$this->user}, the password is {$this->pwd}";
}
}
$a =new account ();
echo $a;
Echo Php_eol;
Print_r ($a);

Running this code reveals that the output results are customizable and easier to understand after using the ToString method. In fact, the design prototype of the ToString Magic method of PHP comes from Java. Java also has such a method, and in Java, this method is used extensively, for debugging programs is more convenient. In fact, the ToString method is also a serialization, we know that PHP comes with Serialize/unserialize is also serialized, but this set of functions serialization will produce some useless information, such as the length of the property string, resulting in unnecessary waste of storage space. Therefore, you can implement your own serialization and deserialization methods, or Json_encode/json_decode is a good choice.

Why does the Echo object directly report a syntax error, and if the object implements the ToString method, it can be output directly? The reason is very simple, echo could have printed an object, but also implemented the interface, but PHP has made a restriction, only after the implementation of ToString is allowed to use. From the following PHP source code can be verified:

Zend_vm_handler (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 to convert the object to a string
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 ();
}
  • Related Article

    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.