<?php
class A{
private $n1;
private $n2;
private $n3;
public __set($p_name,$p_v){
$this->p_name=$p_v;
}
pubilc __get($p_name){
if(isset($p_name)){
return $this->p_name
}else{
return null;
}
}
}
$a1=new A();
$a1->$n1="hhh";
echo $a1->n1;
?>
继承
<?php
class P{
public $n;
protected $a;
public function showInfo(){
echo $this->n."||".$this->a;
}
public function t(){
echo "小学生";
}
}
class graduate(){
public $n;
protected $a;
public function showInfo(){
echo $this->n."||".$this->a;
}
public function t(){
echo "大学生";
}
}
(代码复用性不高)
解决:
//父类
class stu(){
public $n;
protected $a;
public functon __construct();
public function showInfo(){
echo $this->n."||".$this->a;
}
}
//子 类
class P extends stu{
public function tsting(){
echo "小学生";
}
}
class graduate extecds stu{
public function testing(){
echo "大学生";
}
}
$stu1=new p();
$stu->n="小米";
$stu1->testing();
$stu1->showInfo();
$stu2=new grduate();
$stu2->n="大米";
$stu2->testing();
$stu2->showInfo();
继承 (public/protected) extecds
基本语法
class 类名 extecds父类名{
再写自己需要的属性和方法
}
?>
<?php
class A{
public $n1=1;
protected $n2="hhh";
private $n3=11.2;
public function test1(){
echo "test1()";
}
proected function test2(){
echo"test2()";
}
private function test3(){
echo "test3()";
}
}
class sudclass extends A{
function show(){
//echo $this->n2;
//echo $this->n3;
$this->test2();
}
}
//创建subclass对性
$sub1=new sudclass();
//echo $sud1->n1;
$sud1->test1();
//echo $sud1->show;
$sud1->show;
?>
<?php
class A{
public function __construct(){
echo "A__construct";
}
}
class B extends A{
function __construct(){
echo "B__construct";
}
}
//创建B类对象实例
$b=new B();
?>
了解
如果我们希望去调用父类的 构造方法 ,或者其他方法(public/protected),
可以这样处理
类名::方法名()
parent::方法名
举例
class A{
public $n1=90;
//构造方法
public function __construct(){
echo "A__construct";
}
}
class B extends A{
function __construct(){
echo "B__construct";
//显式的调用父类的方法
//A::__construct();
parent::__construct();
}
}
当一个子类和父类的方法完全一样(public/protected)我们称为方法的覆盖