Jump to Navigation

033 - OOP Setting properties

PHP5 version 5 and newer does offer some semblance of support for properties, done by overloading the __set and
__get methods. These methods are invoked if you attempt to reference a member variable that does not exist
within the class definition. Properties can be used for variety of purposes, such as to invoke an error message,
or even to extend the class by actually creating new variables on the fly.

__set() Example:

class Employee
{
var $name;
function __set($propName, $propValue)
{
$this->$propName = $propValue;
}
}

$employee = new Employee();
$employee->name = "Mario";
$employee->title = "CEO";
echo "Name: " . $employee->name;
echo "<br />";
echo "Title: " . $employee->title;
----------------------------------------------------------------------------------
Name: Mario
Title: CEO

__get() Example:

class Employee
{
var $name;
var $city;
protected $wage;
function __get($propName)
{
echo "__get called!<br />";
$vars = array("name", "city");
if (in_array($propName, $vars))
{
return $title->$propName;
}else{
return "No such variable!";
}
}
}
$employee = new Employee();
$employee->name = "Mario"

echo $employee->name . "<br / >";
echo $employee->age;

---------------------------------------------------------------------------
Mario
__get called!
No such variable!

 

PHP:


Main menu 2

Story | by Dr. Radut