<?php //类常量 header("Content-type: text/html; charset=utf-8"); class Person{ private $name; const HOST = 'localhost';//定义常量,最好是大写,前面没有$符号 public function __construct($name='',$age=18){ $this->name = $name; $this->age = $age; } public function say(){ echo "my name is {$this->name}"; } } $p1 = new Person("lisi",25); $p1->say(); echo Person::HOST;//类常量是属于类的,不能用对象调用,只能用类调用 //静态属性 class Person{ public $name; static public $num;//用于计算new了几个对象 function __construct($n){ $this->name = $n; //Person::$num++;//静态属性只能类本身调用,对象不能调用 self::$num++;//self代表类本身 } public function say(){ echo "my name is {$this->name}"; } } $obj = new Person("user1"); $obj = new Person("user2"); $obj = new Person("user3"); echo Person::$num; //静态方法 class Person{ public $name; static public $num;//用于计算new了几个对象 function __construct($n){ $this->name = $n; //Person::$num++;//静态属性只能类本身调用,对象不能调用 self::$num++;//self代表类本身 } public function say(){ echo "my name is {$this->name}"; } static public function sum($i,$j){//定义方法是static,则该方法不依托于对象,直接可以用类调用 return $i+$j; } } echo Person::sum(5,10); ?>
魔术方法
<?php header("Content-type: text/html; charset=utf-8"); class Person{ private $name; public $age; public function __construct($name='',$age=18){ $this->name =$name; $this->age =$age; } private function text(){ echo "Person->test()"; } public function __toString(){ return "这是我定义的解决什么问题的类"; } public function __call($i,$j){ echo "你调用了一个没有定义的方法{$i},{$j[1]}"; } public function __get($i){ echo "你访问了一个没有权限访问的属性{$i}"; } public function __set($i,$j){ echo "你无法设置了一个没有定义权限访问的属性{$i},{$j}"; } public function __isset($i){ echo "你无法判断{$i}是否存在"; } public function __unset($i){ echo "111"; } } $p1 = new Person("lisi",25); //$p1->getName("张三","lisi"); //isset($p1->address); //unset($p1->age); $str = $p1->address; echo $str; ?>