第70讲 static关键字静态变量

来源:互联网 发布:ff14猫女捏脸数据 御姐 编辑:程序博客网 时间:2024/06/05 11:40

Static(静态)关键字

==Tip==
本页说明了用 static 关键字来定义静态方法和属性。static 也可用于定义静态变量以及后期静态绑定。参见上述页面了解 static 在其中的用法。

  • 声明类属性或方法为静态,就可以不实例化类而直接访问。静态属性不能通过一个类已实例化的对象来访问(但静态方法可以)。

  • 兼容php 4 如果没有指定访问控制符 ,属性和方法通通默认公有

  • 静态方法不需要对象就可以调用,所以 伪变量 $this 在静态方法中不可用
  • 静态属性不可以由对象通过 -> 操作符来访问。
  • 用静态方式调用一个非静态方法会导致一个 E_STRICT 级别的错误

global 方式:

<?php    global $global_nums;    $global_nums=0;    class Child{        public $name;        function __construct($name){            $this->name=$name;        }        public function join_game(){            global $global_nums;            $global_nums++;            echo $this->name."加入堆雪人游戏<br/>"."多少人?".$global_nums."<br/>";        }    }    $child1 = new Child("张飞");    $child1->join_game();    $child2 = new Child("李逵");    $child2->join_game();    $child3 = new Child("唐僧");    $child3->join_game();?>

static 方式:

<?php    class ChildStatic{        public $name;        public static $nums;        public static $my_static="foo";        public function __construct($name){            $this->name=$name;        }        public function join_game(){            self::$nums++;            echo $this->name."玩游戏<br/>";        }    }    $childStatic1 = new ChildStatic("李白");    $childStatic1->join_game();    $childStatic2 = new ChildStatic("钟馗");    $childStatic2->join_game();    $childStatic3 = new ChildStatic("程咬金");    $childStatic3->join_game();    echo "总共".ChildStatic::$nums."人玩游戏";    $className = "ChildStatic";    echo "总共".$className::$nums."人玩游戏";    //echo "总共".$childStatic3->my_static."人玩游戏";//这种调用方式 错了 但是 手册上有用对象直接调用的为啥不行 my_static 带不带 $ 都会出错  直接报了notice 貌似是不是能调用 但是未定义啥的 目前不让使唤?  ----- 不能写法。。。。。。。。。。。?>

==static 定义的变量 在类的内部 用 self::xx;访:xx访问== 具体请参考php使用手册

原创粉丝点击