代码之家  ›  专栏  ›  技术社区  ›  yarek

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

php
  •  0
  • yarek  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  2
  •   Vivick    7 年前

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

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

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

    static::$table

        2
  •  1
  •   Lajos Veres    7 年前

    你想用 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::不会使用定义方法的类来解析,而是使用运行时信息来计算。它也被称为“静态绑定”,因为它可以用于(但不限于)静态方法调用。

    推荐文章