yarek
yarek

Reputation: 12064

php: how to get static variable from inherited Class?

Here is the code:

class Crud {
 public static function get($id);
 echo "select * from ".self::$table." where id=$id";// here is the problem
}

class Player extends Crud {
 public static $table="user"
}


Player::get(1);

I could use Player::$table, but Crud will be inherited in many classes.

Any idea ?

Upvotes: 0

Views: 45

Answers (2)

Lajos Veres
Lajos Veres

Reputation: 13725

You want to use static:

<?php
class Crud {
    public static $table="crud";
    public static function test() {
       print "Self: ".self::$table."\n";
       print "Static: ".static::$table."\n";
    }
}

class Player extends Crud {
    public static $table="user";
}

Player::test();

$ php x.php 
Self: crud
Static: user

Some explanation from the documentation: http://php.net/manual/en/language.oop5.late-static-bindings.php

"Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

Upvotes: 1

Vivick
Vivick

Reputation: 4991

To refer to static members in PHP there are two keywords :

  • self for "static" binding (the class where it is used)

  • static for "dynamic"/late static binding (the "leaf" class)

In your case you want to use static::$table

Upvotes: 2

Related Questions