Heim > Fragen und Antworten > Hauptteil
难道子类静态方法没有办法调用父类非静态方法吗?
迷茫2017-06-08 11:03:40
你这么用的显然很不规范, 当然先说正题.
要调父类的非静态方法, 首先你得取到类实例
如果有缓存就直接拿, 没有就创建一个
$instance = new self();
$totalCount = $instance->get_one_bysql($sqlstr);
滿天的星座2017-06-08 11:03:40
打开注释玩玩就知道了
<?php
class a{
public $ab = NULL;
public function d(){
var_dump($this->ab);
}
public function c($a,$b){
var_dump($a+$b);
}
}
class b extends a{
public static function t(){
// $this->d(); //Fatal error: Using $this when not in object context in D:\phpStudy\WWW\index.php on line 14
// $this->c(1,2); //Fatal error: Using $this when not in object context in D:\phpStudy\WWW\index.php on line 15
// self::d(); //Strict Standards: Non-static method a::d() should not be called statically in D:\phpStudy\WWW\index.php on line 16
//Fatal error: Using $this when not in object context in D:\phpStudy\WWW\index.php on line 5
// self::c(1,2); //Strict Standards: Non-static method a::c() should not be called statically in D:\phpStudy\WWW\index.php on line 18
// int(3)
// parent::d(); //Strict Standards: Non-static method a::d() should not be called statically in D:\phpStudy\WWW\index.php on line 20
// Fatal error: Using $this when not in object context in D:\phpStudy\WWW\index.php on line 5
// parent::c(1,2); //Strict Standards: Non-static method a::c() should not be called statically in D:\phpStudy\WWW\index.php on line 22
//int(3)
}
}
b::t();
总结:this用于实例调用。self,parent用于调用静态属性或方法。
最后一个奇特的现象是虽然静态调用父类的非静态方法处理数据,会得到一个报错,但是还是输出了int(3)