Home > OS >  How to define a class in php that accepts unlimited properties directly
How to define a class in php that accepts unlimited properties directly

Time:01-31

in Laravel model, for instance, a class User can be initialized and properties set like below

$u =  new User;
$u->name='Name';

But if I create a class in PHP like below

class X {}

$x = new X;

if I try to set other properties like below

$x->name='name';

I will receive an error telling me that the property name is not defined in class X

My question is how is it done? so that I can create a class and then be able to add properties as whenever the class is initialized even if the property does not already exist in the class

CodePudding user response:

You can use magic getters & setters from PHP, methods __get() and __set().

class X {
  public function __set($name, $value) {
    $this->$name = $value;
  }
  public function __get($name) {
    return $this->$name;
  }
}

$x = new X();
$x->name = "Guille";
echo $x->name; // Prints Guille

Also remember that dynamic properties are deprecaded on PHP 8.2.

To allow dynamic properties on PHP 8.2 use:

#[AllowDynamicProperties]
class X {
  // ...
}

CodePudding user response:

If you want an "unlimited" property class, even without defining a class and the contents, then just use new \stdClass():

class A
{
   public $property1;
   public $property2;
   //...
}

// VS

$class = new \stdClass();

$class->property1 = 'abc';
$class->property1000000 = true;
$class->propertyABC = [1, 2, 3, 4, 5];

But I think you don't want anything like this, you should AVOID using stdClass and classes that magically set stuff using __get and __set, because you MUST know by memory, what it has. It is considered a very BAD practice...

I am not sure why you need to dynamically set stuff, but maybe a Collection or an array will solve your issue.

  • Related