PHP的:如何从继承的类中获取静态变量?

时间:2018-12-22 12:16:21

标签: php

代码如下:

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

我可以使用Player :: $ table,但是Crud将在许多类中继承。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

要在PHP中引用静态成员,有两个关键字:

  • self用于“静态”绑定(使用它的类)

  • static用于“动态” /后期静态绑定(“叶”类)

您要使用static::$table

答案 1 :(得分:1)

您要使用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

文档中的一些解释: http://php.net/manual/en/language.oop5.late-static-bindings.php

  

“后期绑定”来自以下事实:static ::不会使用定义方法的类来解析,而是使用运行时信息来计算。它也被称为“静态绑定”,因为它可用于(但不限于)静态方法调用。

相关问题