Controlling How Your Variables Are Handled In a PHP Class

There are many ways that you can control how variables are accessed in your Class. The most common is using Constants but the problem is that constants are public an can be accessed using:


Let say you want to have more control of your variables. One way you can do this is a great suggestion that I find in Stack Overflow – Are private constants possible in PHP? The suggestion made by Madbreaks is brilliant!

The other option is the one I’ve been using for quite sometime.

  1. Make all your variable private or protected
  2. Filter how variables a set using a custom function

To make your private or protected variables is as easy as:

protected $default = "default value";

Then you need to create your function, for this I set another private static variable with a regEx pattern with a list of variables I don’t want the value to be changed.

    private static $protected_public_variables = "/^err$|^message$|^systemInfo$/";
    private $message = array();
    private $systemInfo;
    private $err = array();
    pravate $changeMe;

With this set, then create your public protected function:

    private protected function setVar($var){
            foreach($var as $k=>$v){
                    $this->{$k} = (is_number($v) || is_array($v) || is_object($v) || is_bool($v))? $v : htmlspecialchars($v);
                } else {
                    $this->err[] = "Variable $k cannot be set!";
        } else {
            $this->err[] = "Parameters should be set as an array";

To use this function you can add it to your __construct() function like:

public function __construct($arr=null) {
        if(is_array($arr)) $this->setVar($arr);
        if(count($this->err) > 0){
              throw new Exception("<ul><li>".join("</li><li>",$this->err)."</li></ul>","400");

Just make sure that all variables are set as an array like:

     $array = {
        'changeMe' => 'Hello World!',
        'err' => 'error',
        'message' => 'Hello World!',
     $foo = new FOO($array);

This should throw you an error because the variables err and message are been trying to be set up by the Class call.

Hope this would help… Happy Coding!

Leave a Reply