D
D
devastation_kvlt2016-04-30 21:34:37
PHP
devastation_kvlt, 2016-04-30 21:34:37

Is it possible to change a class property?

Есть класс, который нельзя править
Class Test{
public q=5;
}

Is it possible to change the value q=9 after declaring a class so that all new objects are created with q=9?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
profesor08, 2016-04-30
@devastation_kvlt

You should define this variable as static.

class Test
{
  public static $p = 5;
  public static print()
  {
     echo self::$p;
  }
}

Test::$p = 9;

$obj = new Test();
$obj->print(); // 9

Or do it a little differently, but depending on what is more convenient for you
class Test
{
  private static $_p = 5;

  public $p;

  public function __construct()
  {
    $this->p = self::$_p;
  }

  public function update($value)
  {
    $this->p = $value;
    self::$_p = $value;
  }

  public static print()
  {
     echo $this->p;
  }
}

$obj = new Test();
$obj->update(9);
$obj->print(); // 9

G
GavriKos, 2016-04-30
@GavriKos

Well, as an option - make a class-successor from Test, and in the constructor of the class-successor redefine the value of q. Everywhere then use the successor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question