WordPress PHP Extended Classes Refer to 'Wrong' Static Variables

96 views Asked by At

I have a WordPress plugin with 2 extended classes, Area and Loc, each of which has a helper function Get. Each class has static variables for table_name. If I call Loc::Get($id) directly, it works as expected. If, however, I call Loc::Get($id) from Area, it uses the table_name from Area rather than Location.

Can anyone explain how to correct this? Regards,

class _Base {
    function Get($id) {
        $instance = new self();
        $sql = "SELECT * FROM " . static::$table_name . " WHERE id=$id";
        return $sql;
    }
}

class Area extends _Base {
    static $table_name = "Area";
    function getLoc($id) {
        $sql = Loc::Get($id);
        return $sql;
    }
}

class Loc extends _Base {
    static $table_name = "Loc";
}

$sql = Area::Get(1); // -> "SELECT * FROM **Area** WHERE id=1"

$sql = Loc::Get(1); // -> "SELECT * FROM **Loc** WHERE id=1"

$sql = $area->GetLoc(1); // -> "SELECT * FROM **Area** WHERE id=1"
2

There are 2 answers

0
stepozer On BEST ANSWER

I think your problem is you run NON static method Get as static. When i changed it then all start work fine. Try my code below:

<?php
class _Base {
    static function Get($id) {
        $instance = new self();
        $sql = "SELECT * FROM " . static::$table_name . " WHERE id=$id";
        return $sql;
    }
}

class Area extends _Base {
    static $table_name = "Area";
    function getLoc($id) {
        return Loc::Get($id);
    }
}

class Loc extends _Base {
    static $table_name = "Loc";
}

var_dump(Area::Get(1));
var_dump(Loc::Get(1));
var_dump((new Area)->getLoc(1));
0
Leandro Papasidero On

First

Function Get is not static by definition function Get($id) {

Second

$area is not defined