<?php
class A{
//私有属性 无法访问
private $name;
private $sex;
private $age;
//给没有权限访问的属性赋值的时候自动调用
public function __set($key,$value){
//echo 'key===>'.$key.'<br/>';
//echo 'value====>'.$value.'<br/>';
$this->$key = $value;
}
//访问没有权限的属性时候自动调用
public function __get($key){
//echo 'key====>'.$key.'<br>';
// if($key == 'name'){
// //return $this->$key;
// return '王根基';
// }
// if($key =='age'){
// return 18;
// }
// if( $key== 'sex'){
// return '不男不女';
// }
return $this->$key;
}
// public function setName($name){
// $this->name = $name;
// }
// public function setSex($sex){
// $this->sex = $sex;
// }
// public function setAge($age){
// $this->age = $age;
// }
// public function getName(){
// return $this->name;
// }
// public function getAge(){
// return $this->age;
// }
// public function getSex(){
return $this->sex;
// }
}
$a = new A;
echo '<hr/>';
//给属性赋值
// $a->setName('金链');
// $a->setAge('19');
// $a->setSex('母');
$a->name='金链';
$a->age = 19;
$a->sex = '母';
var_dump($a);
//访问属性
echo $a->name.'<br/>';
echo $a->age.'<br/>';
echo $a->sex.'<br/>';
// echo $a->getName().'<br/>';
// echo $a->getAge().'<br/>';
// echo $a->getSex().'<br/>';点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号