PHP Create Read-Only Properties for your Class

To create read-only properties for your class, you will have to use the

__get()

and

__set()

functions. You just have to create the framework and code to implement this functionality.

Here’s a quick example: (This code doesn’t take advantage of the “type” attribute in the properties array, but is there for ideas)

    <?php

class Test {
   
    private $p_arrPublicProperties = array(
            "id" => array("value" => 4,
                    "type" => "int",
                    "readonly" => true),
            "datetime" => array("value" => "Tue 02/21/2006 20:49:23",
                    "type" => "string",
                    "readonly" => true),
            "data" => array("value" => "foo",
                    "type" => "string",
                    "readonly" => false)
            );

    private function __get($strProperty) {
        //Get a property:
        if (isset($this->p_arrPublicProperties[$strProperty])) {
            return $this->p_arrPublicProperties[$strProperty]["value"];
        } else {
            throw new Exception("Property not defined");
            return false;
        }
    }
   
    private function __set($strProperty, $varValue) {
        //Set a property to a value:
        if (isset($this->p_arrPublicProperties[$strProperty])) {
            //Check if property is read-only:
            if ($this->p_arrPublicProperties[$strProperty]["readonly"]) {
                throw new Exception("Property is read-only");
                return false;
            } else {
                $this->p_arrPublicProperties[$strProperty]["value"] = $varValue;
                return true;
            }
        } else {
            throw new Exception("Property not defined");
            return false;
        }
    }
   
    private function __isset($strProperty) {
        //Determine if property is set:
        return isset($this->p_arrPublicProperties[$strProperty]);
    }
   
    private function __unset($strProperty) {
        //Unset (remove) a property:
        unset($this->p_arrPublicProperties[$strProperty]);
    }  
           
}

$objTest = new Test();

print $objTest->data . "\n";

$objTest->data = "bar"; //Works.
print $objTest->data;

$objTest->id = 5; //Error: Property is read-only.

?>

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>