skip to Main Content

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

2

Answers


  1. 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 {
      // ...
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search