编程1: 类声明与类的实例化;
实例
<?php class Demo1{ } //用new实例化一个类 $demo1=new Demo1(); $demo1->name='老师'; $demo1->gender='1'; $demo1->hello=function(){ return 'Hello World.'; }; echo $demo1->name,':',$demo1->gender,'<br>'; echo call_user_func($demo1->hello);
运行实例 »
点击 "运行实例" 按钮查看在线实例
编程2: 类常量与类属性的重载;
实例
<?php class Demo2{ public $name; public $salary=6000; protected $gender =0; private $age=33; public function getSex(){ return ($this->gender==0)?'Male':'Female'; } public function getAge() { return ($this->gender == 0) ? $this->age : 'Secret.'; } } $demo2=new Demo2(); var_dump(is_null($demo2->name)); echo 'gender:',$demo2->getSex(),'<br>'; echo 'age:', $demo2->getAge(), '<br>';
运行实例 »
点击 "运行实例" 按钮查看在线实例
编程3: 类的继承与方法重写;
实例
<?php class Demo4 { public $name; protected $age; private $salary; const APP_NAME='TEG'; //parent public function __construct($name, $age) { $this->name=$name; $this->age=$age; } public function __get($name) { if(isset($this->$name)){ return $this->$name; } return 'illegal'; } } class DemoSon extends Demo4{ // private $gender; const APP_NAME='CRRC'; public function __construct($VarName,$varAge,$varGender='0') { parent::__construct($VarName, $varAge); $this->gender= $varGender; } //get 方法要写到最终类之中 public function __get($name) { if (isset($this->$name)) { return $this->$name; } return 'illegal'; } } $demoSon=new DemoSon('CRRC','50'); echo $demoSon->gender;
运行实例 »
点击 "运行实例" 按钮查看在线实例
编程4: 类中静态成员的声明与访问
实例
<?php //静态变量 class Demo5{ public static $pdo=null; protected static $db=[ 'type'=>'mysql', 'host'=>'localhost', 'dbname'=>'php', 'user'=>'root', 'password'=>'root123' ]; public static function connect(){ $dsn= self::$db['type'].':host='. self::$db['host'].';dbname='. self::$db['dbname']; self::$pdo=new PDO($dsn, self::$db['user'], self::$db['password']); } public static function select($table,$fields='*',$num=5){ $stmt= self::$pdo->prepare("SELECT {$fields} FROM {$table} LIMIT{$num}"); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } Demo5::connect(); $result= Demo5::select('staff', '*', 5); echo '<pre>'; var_export($result);
运行实例 »
点击 "运行实例" 按钮查看在线实例