- auto.php 文件
<?php
spl_autoload_register(
function($className){
// $className 是new的Son这个名字,这个名字是类名,不是文件名
require $className . '.php';
}
);
- 抽象类Animal文件animal.php
<?php
abstract class Animal{
public $name;
protected $age;
protected $sound;
protected $count;
protected $color;
abstract public function shout();
public function __get($key){
if($key=='sound'|| $key=='count'){
$resout= $this->$key;
}elseif(isset($this->$key)){
$resout= "您访问的成员不能访问";
}else{
$resout= "您访问的成员不存在。";
}
return $resout;
}
public function __set($key,$value){
if($key=='sound' or $key=='count'){
return $this->$key=$value;
}
echo "您不可以设置$key 这个成员。";
}
//__call 处理没有定义的方法
public function __call($name, $arguments)
{
$count=count($arguments);
$resout="您访问的方法:$name. 传入{$count}个参数,";
if($count>0){
foreach($arguments as $arg){
$resout .=$arg .",";
}
}
$resout .="该方法不存在。";
return $resout;
}
//访问未定义的静态方法,触发__callStatic方法
public static function __callStatic($name, $arguments)
{
return "方法$name 不存在。";
}
}
- dog.php文件,定义了Dog类
<?php
require_once "auto.php";
class Dog extends Animal{
public function shout()
{
$res="我的名字叫:".$this->name.",我{$this->age}岁了,";
for($i=0;$i<$this->count;$i++){
$res.=$this->sound." ";
}
return $res;
}
public function __construct($name,$sound="",$age=3)
{
$this->name=$name;
$this->age=$age;
$this->sound=$sound;
}
}
- 接口文件 fly.php
<?php
interface Fly{
public function canFly();
}
- 实现接口的类文件:EspecialDog.php
<?php
require_once "auto.php";
//继承类,实现接口
class EspecialDog extends Dog implements Fly{
public function canFly()
{
return "我是$this->name,我会飞";
}
}
- 练习
```php
<?php
require_once “auto.php”;
$d=new Dog(‘阿黄’,”汪”,3);
echo $d->name;
echo “<HR>“;
echo $d->sound;
echo “<HR>“;
echo $d->age;
echo “<HR>“;
//设置叫的次数
$d->count=5;
echo $d->shout();
echo “<HR>“;
echo $d->aa;
echo “<HR>“;
//设置一个不存在的成员,给出提示“您不可以设置a 这个成员”
$d->a=”aaa”;
echo “<HR>“;
echo $d->f(100,33);
echo “<hr>“;
$edog=new EspecialDog(“哮天犬”);
echo $edog->canFly();
```
- 结果