How to disable dynamic properties on php objects, have them behave like undefined variables

583 Views Asked by At

Usually, when you access a property of a class that doesn't exist, it has no meaning to that class and it is likely a typo. Using a normal variable that doesn't exist raises a warning for that reason.

Of course, there are plenty of use-cases where automatic properties are helpful, but I find that in the general case, it causes a lot of unclear and silent bugs, where you'd want a warning or error.

I found a way that allows an error to be raised dynamically, but it seems rather convoluted (maybe I can turn it into a trait). Besides, it'd be nice to get a warning or error during parsing/compilation. I've seen this reported some 10 years ago already, is there a better way of doing this since (like a compiler switch or something)?

Note, sealing the class doesn't help here either.

class Foo {
    public $rowNumber;
    public $modificationDate;
    public $userName;

    // seal the class for dynamic properties
    public function __set($name, $value) { 
        die("Cannot set property '$name' to '$value', property does not exist\n"); 
    }

    public function __get($name) { 
        die("Cannot get value for property '$name', property does not exist\n"); 
    }
}

$x = new Foo();
$x->rowNumber = 42;
$x->modDate = "2022-12-12";     // raises error with the __set function present, otherwise nothing happens
print_r($foo);                  // raises standard warning from PHP, which is helpful
print_r($x);
1

There are 1 best solutions below

0
Tac Tacelosky On

PHP 8.2 (released after this question was asked) deprecates dynamic properties.

I was trying to find what triggered the deprecation error in my code (nested deep in a trait), and solved that with your suggestion of using __set:

public function __set($property, $value) {
    assert(false, $property . " does not exist.");
}