<?php /** * Created by PhpStorm. */ class People { //支持带参数 //类的构造方法 /** * Man constructor. * @param int 年龄 * @param String 名字 * @param String 性别 */ public function __construct($age, $name,$sex) { // echo '<br>'; // echo 'Man的构造方法输出'; $this->_age = $age; $this->_name = $name; $this->_sex=$sex; People::$NUM++; if (People::$NUM > People::MAX_MAN_NUM) { throw new Exception("不能创建太多的人"); } } private $_age, $_name,$_sex; public function getAge() { return $this->_age; } public function getName() { return $this->_name; } private static $NUM = 0; //声明常量 const const MAX_MAN_NUM = 200; //静态方法static public static function sayHello() { echo '这是个静态方法'; } }
这是一个典型的类的声明
解决类名的冲突可以使用命名空间 namespace
<?php /** * Created by PhpStorm. * 解决类的重名 */ namespace jikexueyuan; class Hello1 { public function sayHello() { echo '<br>'; echo '这个是在命名空间jikexueyuan下的Hello1类的sayHello方法'; } }
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body> 8 <?php 9 /** 10 * Created by PhpStorm.14 */ 15 use jikexueyuanHello1; 16 17 require_once 'Hello.php'; 18 19 $h = new Hello(); 20 $h->sayHello(); 21 22 echo '<br>'; 23 $d = new Desktop(); 24 $d->Work(); 25 26 require_once 'jikexueyuan/Hello1.php'; 27 $a = new Hello1(); 28 $a->sayHello(); 29 30 31 require_once 'Man.php'; 32 $m = new Man(10, "极客学院"); 33 echo '<br>'; 34 echo $m->getName(); 35 echo '<br>'; 36 echo Man::sayHello(); 37 for ($i = 0; $i < Man::MAX_MAN_NUM - 1; $i++) { 38 new Man(10, "极客学院"); 39 } 40 date_default_timezone_set('Asia/Shanghai'); 41 echo date('Y-m-d H:i:s'); 42 ?> 43 </body> 44 </html>