About PHP _set () and _get ()

Source: Internet
Author: User
About PHP _set () and _get ()
It is said on the net that these two functions are used for private variables, is this not a violation of the encapsulation of classes?
Why sometimes use $this-> $varName, sometimes such $this->varname is to want not "$" ah???
If you have time, help me to see where my code is wrong:
Class MyClass
{
Private $Age;
Private $Grade;
Public function __construct ($name)
{
$this->myname = $name;
$this->age = 5;
}
Public Function _get ($property _name)
{
Echo ' Access to _get ()
';
if (Isset ($property _name))
{
return $this $property _name;
}
}
Public Function _set ($property _name, $value)
{
Echo ' Access to _set ()
';
$this $property _name = $value;

}
}
$obj = new MyClass (' Tom ');
$obj->age = 23;//said this wrong $obj $Age is also an error
?>

------Solution--------------------
The error is not out of the $ there.
First you define a class private member variable, which can only be called within the class itself.
$obj->age = 23; obviously cannot be called because the permission is not enough, external prohibit call.
$obj-$Age = 23; It is also wrong, first of all, PHP will automatically recognize your $age discovery is empty, and plainly equivalent to $obj->=23;
To change the code for you, it is estimated that you understand that at the moment you do not understand the class variable invocation level.

PHP Code
  
   MyName = $name; $this->age = 5;} Public Function _get ($property _name) {echo ' Access _get ()
'; if (Isset ($property _name)) {return $this, $property _name;}} Public Function _set ($property _name, $value) {echo ' Access _set ()
'; $this $property _name = $value;}} $obj = new MyClass (' Tom ');//$obj->age = at $obj->_set (' Age ', ' "Hello World"), Echo $obj->_get (' age '); $Age = ' Test '; $obj $Age = ' Hello Difa '; echo $obj->test;
  • 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.