Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid dynamic properties in PHP (raise an Error when setting an undeclared property)

Example:

error_reporting(E_ALL | E_STRICT);
class Test {}
$obj = new Test();
$obj->undeclared = "oops";    // I want an error here !! :(
echo $obj->algo;              // oops 

I tested it on PHP 5.2.11 and 5.3.0.

I don't want dynamic properties in my objects.
Is possible to force PHP to raise an ERROR in that situation ?

like image 847
Enrique Avatar asked Feb 03 '12 22:02

Enrique


2 Answers

Use __set() ?

<?php
class Test {

    public $bar;

    public function __set($name, $value) {
        throw new Exception('Cant set!');
    }
}

$obj = new Test;
$obj->bar = 'foo';
$obj->foo = 'evil';
?>
like image 152
radmen Avatar answered Sep 29 '22 08:09

radmen


A bit more diligence with your error message and you can help your own coding. Having the following as your base class setup will:

  1. protect uses of this class from overwriting your properties
  2. protect misspellings of variables (especially camel-case mistakes) for instance $this->callerID returns as expected but $this->callerId throws an exception and prevents code errors.
    public function __set($name,$value) {
        switch ($name) {
            default:
                // we don't allow any magic properties set or overwriting our properties
                try {
                    $error = "Assignment of {$name} in " . static::class . ' not allowed because it is a magic variable or read-only property.';
                    throw new \RuntimeException($error);
                } catch ( \RuntimeException $e ) {
                    echo 'Caught exception: ' . $e->getMessage() . PHP_EOL;
                }

        }
    }

    public function __get($name)
    {
        switch ($name) {
            default:
                // we don't allow any magic properties
                try {
                    $error = "var {$name} is not a property of " . static::class . '.';
                    throw new \RuntimeException($error);
                } catch ( \RuntimeException $e ) {
                    echo 'Caught exception: ' . $e->getMessage() . PHP_EOL;
                }
        }
        return null;
    }

    public function __isset($name)
    {
        switch ($name) {
            default:
                return false;
        }
    }
like image 45
Brian Becker Avatar answered Sep 29 '22 06:09

Brian Becker