简体   繁体   中英

How can I late static binding in inherited class with variable variables of PHP

The thing is, suppose we have three classes A, B and C. B and C inherit from A.

<?php
class A{
  public static function update(){
    static::$id = 1;
  }
}

class B extends A{
  public static $id_B;
}

class C extends A{
  public static $id_C;
}

A::update();

?>

Because of any reasons, the id's name in B and C are different. The B is id_B, and C is id_C. The class A is kind of interface so it just know the inherited class B and C should have a variable $id. A wants to update $id to 1. What I want is try to update $id_B and $id_C to 1. I tried several methods like set a variable variables like this:

class A{
  public static function update(){
    static::$$id_name = 1;
  }
}

class B extends A{
  public static $id_name="id_B";
  public static $id_B;
}

But it doesn't work. So does anyone can help me solve this design?

Yeah, it just doesn't work like that. Either you know what variable you want to access, or you leave it up to individualised code to do so. For example:

class A {
  public static function update(){
    static::updateId(1);
  }

  protected static function updateId($value) {
    static::$id = $value;
  }
}

class B extends A{
  public static $id_B;

  protected static function updateId($value) {
    static::$id_B = $value;
  }
}

class C extends A{
  public static $id_C;

  protected static function updateId($value) {
    static::$id_C = $value;
  }
}

The syntax you were looking for with your variable variable is:

static::${static::$id_name} = 1;

But I'd suggest using the overloadable methods instead, which affords you more control in the long run. "Interfaces" are best defined by callable functions, not variable names. Whether or not doing this all statically is a good idea to begin with is a different discussion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM