1、this调用父类方法:
2、self调用父类方法:
3、parent调用父类方法:
难道子类静态方法没有办法调用父类非静态方法吗?
你这么用的显然很不规范, 当然先说正题.
要调父类的非静态方法, 首先你得取到类实例
如果有缓存就直接拿, 没有就创建一个
$instance = new self();
$totalCount = $instance->get_one_bysql($sqlstr);
打开注释玩玩就知道了
<?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)
<?php
class a {
public function test() {
echo "a";
}
}
class b extends a {
public function testb() {
$this->test();
}
public static function teststatic() {
$class = new self();
$class->test();
}
}
b::teststatic();
输出a
1 回答4.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
2 回答2.2k 阅读✓ 已解决
2 回答2.2k 阅读
1 回答1.4k 阅读✓ 已解决
796 阅读
646 阅读
self::get_one_by_sql