PHP 靜態方法怎麼呼叫父類別非靜態方法?
淡淡烟草味
淡淡烟草味 2017-06-08 11:01:40
0
5
1015

1、this呼叫父類別方法:

#2、self呼叫父類別方法:

#3、parent呼叫父類別方法:

#難道子類別靜態方法沒有辦法呼叫父類別非靜態方法嗎?

#
淡淡烟草味
淡淡烟草味

全部回覆(5)
Ty80

self::get_one_by_sql

为情所困

先確定下父類別的get_one_bysql 是不是靜態的

關於使用 https://stackoverflow.com/que...

迷茫

你這麼用的顯然很不規範, 當然先說正題.
要調父類的非靜態方法, 首先你得取到類實例
如果有緩存就直接拿, 沒有就創建一個

$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)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!