第70讲 static关键字静态变量
2017-10-18 15:00
351 查看
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使用手册
相关文章推荐
- java中的关键字static(静态变量)和final定义常量
- static关键字理解整理:静态变量、静态函数的作用及使用规则
- static 关键字 成员变量和静态变量的区别 静态使用的注意事项 静态代码块 构造代码块
- 对象创建、static关键字、静态变量和成员变量的区别、文档
- java定义静态变量的作用 static关键字
- Java关键字—static(静态变量、静态方法、静态类)
- 12-面向对象(static关键字-成员变量和静态变量的区别-数据共享 13-面向对象(static关键字-注意事项) 14-面向对象(static关键字-main函数解析 15-面向对象(stat
- C:static 关键字、静态变量、跨类访问数据
- java中的关键字static(静态变量)和final定义常量
- 小东吖 之 java 构造方法 static关键字 静态变量 静态方法
- java中的关键字static(静态变量)和final定义常量
- 3.6 Java static关键字-静态变量
- C#学习笔记之六 类定义中static关键字的用法暨C#中静态变量的意义与使用
- 用static关键字修饰类
- Java关键字final、static使用总结
- C语言中的extern和static关键字详解
- static关键字
- java讲义(五)java中static关键字
- static 关键字
- static和const关键字