Discussion on the understanding and using method of PHP Interceptor (__set) and __get () _php Example

Source: Internet
Author: User
Tags lenovo

"In general, it is more logical to define the attributes of a class as private."

However, read and assign operations on attributes are very frequent, therefore, in PHP5, two functions "__get ()" and "__set ()" are predefined to get and assign their properties, and to check the "__isset ()" of the property and the Method "__unset ()" for deleting the property.

We have set and get methods for each attribute, in PHP5 we provide methods for setting values and fetching values for attributes, "__set ()" and "__get ()", two methods that are not by default, but rather as we add them to the class by hand, such as the construction method (__ Construct ()), just as the class is added to exist, you can add the two methods in the following way, and of course you can add them in a personal style: "

//Interceptor Use
class computer{
private $name;
Private $price;
Private $cpu;
Private $clocked;

Interceptor Assignment Public
function __set ($key, $value) {
//So: $key =name $value = "Lenovo" There are: $this->name= "Lenovo" return
$this-> $key = $value;

Interceptor value public
function __get ($key) {
if isset ($key)) {
//Then: $key =name $this->name so naturally return. " Lenovo "return
$this-> $key;
} else {return
}} It is precisely because of the interceptor exists, can be so used
$computer =new computer ();
$computer->name= "Association";
$computer->cpu= "eight cores";
$computer->clocked= "1600hz";

echo $computer->name;
echo $computer->price;
echo $computer->cpu;
echo $computer->clocked;

The above is a small series for everyone to talk about the PHP Interceptor __set () and __get () the understanding and use of all content, I hope that we support cloud Habitat Community ~

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.