php面向对象关键字

  1. const 修饰类属性
     1 class Person
     2 {
     3     const HOST = 'localhost';
     4 
     5     public function say(){
     6         echo 'hello';
     7     }
     8 }
     9 
    10 echo Person::HOST;
  2. final 最终版本,不允许被继承:修饰类或方法
    1 final class Person
    2 {
    3     const HOST = 'localhost';
    4 
    5     public function say(){
    6         echo 'hello';
    7     }
    8 }
    1 class Person
    2 {
    3     const HOST = 'localhost';
    4 
    5     final public function say(){
    6         echo 'hello';
    7     }
    8 }
  3. static  修饰属性或方法
     1 class Person
     2 {
     3     public $name;
     4     static public $num;
     5 
     6     public function __construct($n){
     7         $this->name = $n;
     8         Person::$num++;
     9     }
    10 }
    11 new Person('user1');
    12 new Person('user2');
    13 new Person('user3');
    14 
    15 echo Person::$num; # 3
     1 # 类名可以直接调用不包含$this的方法,否则必须通过new类名调用
     2 
     3 class Person
     4 {
     5     public $name;
     6 
     7     public function __construct($n){
     8         $this->name = $n;
     9     }
    10 
    11     public function say(){
    12         echo "<p>my name is {$this->name}</p>";
    13     }
    14 
    15     static public function sum($i,$j){
    16         return $i+$j;
    17     }
    18 }
    19 
    20 echo Person::sum(5,25);

猜你喜欢

转载自www.cnblogs.com/yachyu/p/10708296.html
今日推荐