PHP 静态方法怎么调用父类非静态方法?

1、this调用父类方法:

clipboard.png

2、self调用父类方法:

clipboard.png

3、parent调用父类方法:

clipboard.png

难道子类静态方法没有办法调用父类非静态方法吗?

阅读 8.3k
7 个回答

self::get_one_by_sql

你这么用的显然很不规范, 当然先说正题.
要调父类的非静态方法, 首先你得取到类实例
如果有缓存就直接拿, 没有就创建一个

$instance = new self();
$totalCount = $instance->get_one_bysql($sqlstr);

调用不了.

非静态方法需要有$this对象, 从静态方法调用提供不了这个对象.

打开注释玩玩就知道了

<?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

建议楼主先好好学习下面向对象

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题