PHP类中的静态方法使用实例.doc
PHP类中的静态方法使用实例在php中静态方法我们就直接在函数或变量前加一个static就可以了,使用的时候和静态变量差不多,不需要实例化,直接用:调用了,下面我来给大家举几个关于静态方法实例。PHP也不例外!所谓静态方法(属性)就是以static关键词标注的属性或者方法(例如:静态属性public static username;)静态方法和非静态方法最大的区别在于他们的生命周期不同,用一个实例来说明静态方法定义定义静态方法很简单,在声明关键词function之前加上static,例如:代码如下复制代码class Astatic function fun()/ do somathing静态方法使用使用的时候和静态变量差不多,不需要实例化,直接用:调用,例如:代码如下复制代码A:fun()对比普通方法因为静态方法的调用不需要实例化,wxjd.net 所以在静态方法中引用类自身的属性或者方法的时候会出错,也就是形如self和$this是错误的。代码如下复制代码class MyClasspublic $num = 5;function _construct()$this->num = 10;function fun_1()echo "I am a public method named fun_1.n"echo "The num of object is $this->num.n"static function fun_2()echo "I am a static method named fun_2.n"function fun_3($n)echo "The arg is $nn"$m = new MyClass;$m->fun_1();$m->fun_2();$m->fun_3(test);MyClass:fun_1();MyClass:fun_2();MyClass:fun_3(test);输出结果:lchlocalhost:php $ php class_method.phpI am a public method named fun_1.The num of object is 10.I am a static method named fun_2.The arg is testI am a public method named fun_1.PHP Fatal error: Using $this when not in object context in /Users/lch/program/php/class_method.php on line 14再看一实例用一个实例来说明。代码如下复制代码class userpublic static $username; /声明一个静态属性public $password; /声明一个非静态属性function _construct($pwd) echo Username:,self:$username; /输出静态属性self:$username = admin; /为静态属性赋值$this->password = $pwd; /为非静态属性赋值public function show() /输出类属性echo Username:,self:$username;echo Password:,$this->password;public static function sshow()echo Username:,self:$username;echo Password:,$this->password;user:$username = root; / pengyeguoji.com 为赋值user类的静态属性赋值$objUser = new user(123456); /实例化user类$objUser->sshow();unset($objUser);echo Username:,user:$username;/* 输出结果为:* Username:root* Username:admin* Password:123456* Username:admin* */从这里实例中可以看出,静态属性在类实例化以前就起作用了,并且在对象被销毁时静态属性依然可以发挥作用!也因为静态方法的这种属性,所以不能在静态方法中调用非静态属性或者方法接着看1、php类中,rczcqc.com 假设所有的属性与方法的可见性为public,那么在外部访问类的方法或属性时,都必须通过对象【类的实例化过程】来调用。eg:代码如下复制代码class Logpublic $root = DIRECTORY_SEPARATOR;public $logPath = /data/app/www/test-realtime.monitoring.c.kunlun.com/log;public $defaultDir = default;public function writeLog($logName, $logType, $data, $newDir = FALSE)$fileName = ;if (!file_exists($this->logPath)mkdir($this->logPath, 0777);if ($newDir != FALSE)mkdir($this->logPath.$this->root.$newDir, 0777);$fileName = $this->logPath.$this->root.$newDir.$this->root.date(Y-m-d, time()._.$logName._.$logType.log;elsemkdir($this->logPath.$this->root.$this->defaultDir, 0777);$fileName = $this->logPath.$this->root.$this->defaultDir.$this->root.date(Y-m-d, time()._.$logName._.$logType.log;file_put_contents($fileName, date(Y-m-d H:i:s). .$data."n", FILE_APPEND);类的实例化对象的过程:$logObj = new Log();访问类中的方法:$logObj->writeLog($param1, $param2, $param3, $param4);访问类中的属性:echo $logObj->root;2、如果类中的属性前被static关键字修饰时,就不能通过对象来访问被static修饰的属性,但如果是类中的方法被static修饰时则即可以通过对象也可以通过类名:方法名的方式来进行访问。3、如果类中的方法被static修饰则,2144xiaoshuo.com 方法中不能用$this,$this指的是类的实例化对象,由于静态方法不用通过对象就可以调用,所以伪变量$this不可用。