0

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?

  • 1
    I think you've over complicated everything. Unless you need to use `B::$id` separate to `B::$id_B`, what's the reason to define the latter? Just use `$id`. – Marty Feb 09 '15 at 04:01
  • I want to write a database class as A so that if my partner want to control database, he can just only create the inherited classes like B and C to CRUD the database without writing the same CRUD code. But the thing is the ids' name in database may be different such as id_student, id_player. So that struggle me. – Xinran Luo Feb 09 '15 at 18:38

1 Answers1

1

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.

deceze
  • 510,633
  • 85
  • 743
  • 889