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:

echo FOO::CONSTANT;

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){
        if(is_array($var)){
            foreach($var as $k=>$v){
                if(!preg_match(self::$protected_public_variables,$k)){
                    $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!

This entry was posted in Tutorials and tagged , , , , , , by Rafael Vila. Bookmark the permalink.

About Rafael Vila

I'm a Son of God, Father of three extremely awesome sons, husband of my sweetie pie Estella. I work as a Graphic Designer and a Web Developer in a Texan Company called Stealth Products, Inc. I've been blessed with a beautiful family and a great community of Faith. I believe God is the only God, who sent his son Jesus who become our Saviour and Redeemer Christ. The mercy and compassion of God is my daily wonder.