suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Wie ruft eine statische PHP-Methode eine nicht statische Methode der übergeordneten Klasse auf?

1. Dies ruft die übergeordnete Klassenmethode auf:

2. Self ruft die übergeordnete Klassenmethode auf:

3. Parent ruft die übergeordnete Klassenmethode auf:

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

淡淡烟草味淡淡烟草味2795 Tage vor1133

Antworte allen(5)Ich werde antworten

  • PHP中文网

    PHP中文网2017-06-08 11:03:40

    self::get_one_by_sql

    Antwort
    0
  • 为情所困

    为情所困2017-06-08 11:03:40

    先确定下父类的get_one_bysql 是不是静态的

    关于使用 https://stackoverflow.com/que...

    Antwort
    0
  • 迷茫

    迷茫2017-06-08 11:03:40

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

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

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-06-08 11:03:40

    调用不了.

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

    Antwort
    0
  • 滿天的星座

    滿天的星座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)

    Antwort
    0
  • StornierenAntwort