关于PHP的_set()跟_get()

WBOY
Release: 2016-06-13 10:57:23
Original
1026 people have browsed it

关于PHP的_set()和_get()
网上说这两个函数是对私有变量使用,这不是违背类的封装性吗?
为什么有时候用$this->$varName ,有时这样$this->varName到底是要不要‘$’啊???
如果您有时间的话在帮我看下我的代码错在哪里:
class MyClass
{
private $Age;
private $Grade;
public function __construct($name)
{
$this->MyName = $name;
$this->Age = 5;
}
public function _get($property_name)
{
echo '访问_get()
';
if (isset($property_name))
{
return $this->$property_name;
}
}
public function _set($property_name, $value)
{
echo '访问_set()
';
$this->$property_name = $value;

}
}
$obj = new MyClass('Tom');
$obj->Age = 23;//说这边错误 $obj->$Age也是错误
?>

------解决方案--------------------
错误不是出在$那里。
首先你定义的是类私有成员变量,私有的只能类自身内部可以调用。
$obj->Age = 23;明显无法调用,因为权限不够,外部禁止调用。
$obj->$Age = 23;也是错误的,首先php会自动识别你的$Age发现是空,说白了等价于$obj->=23;
给你改了一下代码,估计你就明白了,目前你还没懂类的变量调用级别。

PHP code
<?phpclass MyClass{private $Age;private $Grade;public $test;public function __construct($name){$this->MyName = $name;$this->Age = 5;}public function _get($property_name){echo '访问_get()<br>';if (isset($property_name)){return $this->$property_name;}}public function _set($property_name, $value){echo '访问_set()<br>';$this->$property_name = $value;}}$obj = new MyClass('Tom');//$obj->Age = 23;$obj->_set('Age', 'hello world');echo $obj->_get('Age');$Age = 'test';$obj->$Age = 'hello difa';echo $obj->test;<div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!