Search code examples
phpinstance-variables

PHP: deterring instance variable creation outside the class


In the given PHP class below, I understand that $test will not be accessible from outside this class.

class Resource {
    private $test;
    public function __construct() {
       echo "in init";
       $test = "new val";
    }
}

But we will be able to define, new instance variables as below. Is there a trick to stop this?

$r = new Resource();
$r->val = "value"; 

Solution

  • Using magic methods (namly __set) you can tell the class "if this is not set in here, ignore it", for instance;

    <?php
    
    class Resource {
        private $test;
        public function __construct() {
           echo "in init";
           $this->test = "new val";
        }
    
        public function __set($name, $val)
        {
            // If this variable is in the class, we want to be able to set it
            if (isset($this->{$name})
            {
                $this->{$name} = $val;
            }
            else
            {
                // Do nothing, add an error, anything really
            }
        }
    }
    
    $resource = new Resource();
    $resource->foo = "bar";
    echo $resource->foo; // Will print nothing
    

    For reference, please see the guide