David Refoua
David Refoua

Reputation: 3617

Can I modify non-static properties of a class in PHP before initializing it?

Consider the following code:

class MyClass
{

    public $test = 'foo';

    public function example()
    {
        return $this->test;
    }

}

// What I'm trying to do
MyClass->test = 'bar'; 

$test = new MyClass();
echo $test->example(); // Should return `bar` instead of `foo`.

I want to modify the base Class before initializing it. Is this possible to do in PHP?

(Yes, I know that modifying static properties are possible. I'm curious about the non-static ones.)

Upvotes: 1

Views: 126

Answers (1)

Jeto
Jeto

Reputation: 14927

There is no way to change a property's default value after the class was created. And I'm pretty sure reflection won't allow it either.

Here's what you can do instead:

class MyClass
{
  public static $default_test = 'foo';
  public $test;

  public function __construct()
  {
    $this->test = self::$default_test;
  }

  public function example()
  {
    return $this->test;
  }
}

MyClass::$default_test = 'bar';

$test = new MyClass();
echo $test->example();

Basically, you have a static property that holds the default value, and the constructor sets the property's initial value to it.

Demo: https://3v4l.org/djn3T

A bit confused as to why you wouldn't just pass the value to the class' constructor, though. But you may have your reasons.

Upvotes: 1

Related Questions