Various interceptor usage analysis _php techniques in PHP classes

Source: Internet
Author: User
Tags php class

The examples in this article describe the various interceptor usages in the PHP class. Share to everyone for your reference. The specific usage analysis is as follows:

1, __get ($property) called when accessing an undefined property

Copy Code code as follows:
Class Lanjie
{
function __get ($name)
{
echo $name. "Not found! ";
}
}

$ob = new Lanjie ();
Echo $ob->g;

When we call the object $ob undefined property g, the Interceptor __get () method is invoked to output the "G" not found! ;

2, __set ($property, $value) assigning values to undefined property calls

Copy Code code as follows:
Class Person
{
Private $_age;
Private $_name;
function __set ($name, $value)
{
$method = "Set". Ucfirst ($name);
Echo $method;
if (Method_exists ($this, $method))
{
return $this-> $method ($value);
}
}

function SetName ($name)
{
$this->_name = $name;
if (!is_null ($this->_name))
{
$this->_name = strtoupper ($this->_name);
}
}
function Setage ($age)
{
return $this->_age = (int) $age;
}
}

$p = new Person ();
$p->name = ' Bob ';
Print_r (Array ($p));

Here we can see very clearly that when you assign a value to an undefined ' name ', you Invoke "__set ()"

Others are __call (), __isset (), __unset ();
The most useful and commonly used of these is __call (), which is invoked when an existing method is invoked, and __isset () is invoked when the Isset () function is used on a defined attribute, __unset is invoked when the unset is used on an undefined number

I hope this article will help you with your PHP program design.

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.