这一节主要和大家一起学习public,private,protected这三个关键词以及__get()和__set()
public不多说,它具有所有的访问权限
private 只允许自己本类访问
protected 允许本类和继承类来访问
<?php
class group{
private $name; function __construct($name){ $this->name=$name; } } $p=new group("minerchow"); echo $p->name; ?>
结果系统报错:Fatal error: Cannot access private property group::$name in D:\wamp\www\test\newfile.php on line 9
将上述代码改为:
<?php class group{ private $name; function __construct($name){ $this->name=$name; } function code(){ return $this->name."写代码"; } } $p=new group("minerchow"); echo $p->code(); ?>
因为code()方法默认修饰符为public,所以我们可以访问code()方法来获取私有属性
同时,我们也可以使用__get方法直接获取,并且可以改变原来私有属性内容
<?php class group{ private $name; function __construct($name=''){ $this->name=$name; } function __get($name){ return $this->name."++++"; } function code(){ return $this->name."写代码"; } } $p=new group("minerchow"); echo $p->name; ?>
上面代码输出值为minerchow++++
同时我们可以使用__set()来直接改变私有属性值
<?php class group{ private $name; function __construct($name=''){ $this->name=$name; } function __get($name){ return $this->name."++++"; } function __set($n,$v){ $this->$n=$v; } function code(){ return $this->name."写代码"; } } $p=new group("minerchow"); $p->name="aye江子"; echo $p->name; ?>
$n和$v分别对应了下面的name和aye江子,所以输出值为aye江子++++
最后讲一下protected,protected允许自己类和继承类访问,不允许歪脖应用
<?php class group{ protected $name; function __construct($name=''){ $this->name=$name; } function code(){ return $this->name."写代码"; } } $p=new group("minerchow"); echo $p->name; ?>
上面这段代码报错:Fatal error: Cannot access protected property group::$name in D:\wamp\www\test\newfile.php on line 16
改为下面这段代码即可获取到name值为minerchow
<?php class group{ protected $name; function __construct($name=''){ $this->name=$name; } function code(){ return $this->name."写代码"; } } class group2 extends group{ function mingzi(){ return $this->name; } } $p=new group2("minerchow"); echo $p->mingzi(); ?> 转载请注明来自multifeeling
本文标题:php面向对象详解4
本文地址:http://www.multifeeling.com/archives/142