Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
class Demo
{
private $role='admin';
private $username='admin';
//属性重载
public function __get($name)
{
if($this->role === 'admin'){
return $this->username;
}else{
return '非法访问';
}
}
}
$obj=new Demo();
echo $obj->username;
class Demo
{
protected $data=[
'name'=>'admin',
];
public function __get($name){
$method='get'.ucfirst($name);
if(method_exists($this,$method))return $this->$method($name);
}
public function getName($name){
if(!isset($this->data[$name])){
$this->data[$name]=0;
}else{
return $this->data[$name];
}
}
}
$obj=new Demo();
echo $obj->name;
class Demo
{
protected $data=[
'name'=>'admin',
];
public function __set($name,$value){
$method='set'.ucfirst($name);
if(method_exists($this,$method))return $this->$method($name,$value);
}
public function setEmail($name,$value){
$this->data[$name]=$value;
}
}
$obj=new Demo();
$obj->email='admin@php.cn';
var_dump($obj);
public function __call($name, $arguments)
{
return $name.'<br>'.implode(',',$arguments);
}
$obj=new Demo();
var_dump($obj->hello(1,2,3));
public static function __callStatic($name, $arguments)
{
return $name.'<br>'.implode(',',$arguments);
}
$obj=new Demo();
var_dump(Demo::hello(1,2,3));
不能重复定义
主要就是为了解决全局成员的命名冲突
namespace app1{
class Model{
}
const PATH='app/';
function get(){
}
echo Model::class,'<br>';
echo PATH::class,'<br>';
echo get::class,'<br>';
}
namespace app2{
class Model{
}
const PATH='app/';
function get(){
}
echo Model::class,'<br>';
echo PATH::class,'<br>';
echo get::class,'<br>';
}
全局命名空间
namespace{
class Model{
}
const PATH='app/';
function get(){
}
echo Model::class,'<br>';
echo PATH::class,'<br>';
echo get::class,'<br>';
}
同名空间成员的组织方式
防止一个命名空间的代码过多,可以将同一个命名空间的代码写到多个脚本中
namespace app;
require 'namespce1.php';
require 'namespace2.php';
echo Demo2::class,'<br>';
echo Model::class,'<br>';
子命名空间
```html
namespace Ns1{
class Demo{
}
echo Demo::class,’<br>‘;
// namespace用在空间中,标识当前空间的引用,类似$this或self
// echo namespace\Ns2\Demo::class;
echo Ns2\Demo::class,’<br>‘;
echo Ns2\Ns3\Demo::class,’<br>‘;
echo ‘<hr>‘;
}
namespace Ns1\Ns2{
class Demo{
}
}
namespace Ns1\Ns2\Ns3{
class Demo{
}
}
![](https://img.php.cn/upload/image/333/968/852/1616144775828115.png)
子命名空间访问上级
```html
echo Demo::class,'<br>';
//从子级访问上级
echo \Ns1\Ns2\Demo::class,'<br>';
echo \Ns1\Demo::class,'<br>';
//访问全局
echo \Demo::class,'<br>';