Correction status:Uncorrected
Teacher's comments:
<?php echo '实例化类:'.'<br>'; class Homework1{} $h1=new Homework1(); $h1->name='我不是'; $h1->behavior='我没有'; $h1->res='别乱说'; echo $h1->name.$h1->behavior.$h1->res; $h1->test= function(){ return '素质三连';}; echo call_user_func($h1->test); echo '<hr>'; echo '类常量与属性的重载:'.'<br>'; class Homework2 { public $var1; protected $var2; private $var3; public function __construct($var1,$var2,$var3) { $this->var1 = $var1; $this->var2 = $var2; $this->var3 = $var3; echo $this->show(); } public function __get($name) { if($name=='var3') { return '无权查看'; } else return $this->$name; } public function show() { return $this->var1.$this->var2.$this->var3; } public function __set($name,$value) { if($name=='var2') { return false; } else return $this->$name=$value; } public function __isset($name) { if($name=='var2') { return false; } else return isset($this->$name); } } $h2=new Homework2('我是谁?','我在哪?','我在干什么?'); echo '<br>'; echo $h2->var3.'<br>'; $h2->var2='燃烧我的卡路里'; echo $h2->var2.'<br>'; echo isset($h2->var2)?'存在':'不存在'; echo '<hr>'; echo '类的继承与方法重写:'.'<br>'; class Homework3 { const MONSTER='HUNTER WORLD'; private $name; protected $age; public function __construct($name,$age) { $this->name=$name; $this->age=$age; } } class Homework3_1 extends Homework3 { const MONSTER='MONSTER HUNTER KING WORLD '; private $weapon; public function __construct($name,$age,$weapon) { parent::__construct($name,$age); $this->weapon=$weapon; } public function __get($name) { if(isset($this->$name)) { return $this->$name; } else return '无此属性'; } } $h3=new Homework3_1('猛汉王','33','太刀哥'); echo $h3->weapon.'<br>'; echo Homework3::MONSTER.'<br>'; echo Homework3_1::MONSTER; echo'<hr>';
点击 "运行实例" 按钮查看在线实例
<?php class Mysqlconnect { private static $pdo; private static $info=['db'=>'mysql','host'=>'127.0.0.1','dbname'=>'php','username'=>'root','passwd'=>'']; public static function connect() { $dsn='mysql:host=127.0.0,1;dbname=php'; self::$pdo=new PDO('mysql:host='.self::$info['host'].';dbname='.self::$info['dbname'],self::$info['username'],self::$info['passwd']); self::$pdo->query("set names utf8"); } public static function select($fields='*',$table,$num) { $sql="select $fields from $table limit $num"; $stmt=self::$pdo->prepare($sql); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } Mysqlconnect::connect(); $res=Mysqlconnect::select('*','user',2); print_r($res);
点击 "运行实例" 按钮查看在线实例
call_user_func($c1->hello) 在类外部声明函数时使用回调
类常量:所有对象共享,用类名加范围解析符(::)访问,且默认为公共属性public
构造方法中不仅可以初始化对象属性,还可以调用类方法__construct
子类的构造方法一定要把父类的构造方法重新声明一遍
属性重载方法__get(),__set()等应该设置在最终工作类中 被实例化的类就是工作类
引用父类构造方法 parent::__construct($name,$age)
类常量可以在子类中重写,值不同
用类来访问用范围解析符:: 例如类常量,静态成员。用对象来访问用->
静态成员在类中不能用$this,要用关键字self::