PHP Classes
elePHPant
Icontem

C# getters and setters in PHP: Access class variables with setters and getters

Recommend this page to a friend!
  Info   View files View files (3)   DownloadInstall with Composer Download .zip   Reputation   Support forum (1)   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2011-08-11 (5 years ago) RSS 2.0 feedNot enough user ratingsTotal: 539 This week: 1All time: 5,299 This week: 1,047Up
Version License PHP version Categories
csharp-getter-setter 1.0BSD License5.0PHP 5, Data types, Language
Description Author

This package can access class variables with setter and getter functions.

It provides a base class with __set, __get, __isset, __unset functions that store the variable values in an associative array.

Sub-classes can declare and initialize the values of the class variables so IDE and other documentation extraction tools can still find the variables declared by the class.

Another class is also provided to make the access to class variables a read-only operation, so attempts to alter or unset a class variable throws an exception.

Sub-classes can initialize the values of variables by assigning values to variables with the same names but starting with an underscore character (_).

Innovation Award
PHP Programming Innovation award nominee
August 2011
Number 4


Prize: One copy of the Zend Studio
Setters and getters are functions that can store and retrieve values of class variables. They encapsulate the access to variables, so applications have no direct access to the class variable values.

Classes defined with setter and getter functions often store variables in private arrays or some other opaque data access method. However, this approach prevents IDE or other documentation editing tools to reverse engineer a class definition to know about its variables.

This class provides a solution for this problem by letting developers define simulated variable declarations that IDE and documentation tools can extract, while preserving the encapsulation of the access to the class variable values via the getter and setter functions.

Manuel Lemos
Picture of Artur Graniszewski
  Performance   Level  
Name: Artur Graniszewski <contact>
Classes: 13 packages by
Country: Poland Poland
Innovation award
Innovation award
Nominee: 7x

Winner: 1x

Details
Object-Oriented PHP: Implementation of C# getters and setters in PHP
========================================================================

PHP 5 and C# .NET have a getter and setter method feature, making it look like we’re accessing the data member directly. As you probably know, in C# you can define getters and setters for the properties of an object like this:

-------------------------------------------------
public class Person
{
    //default constructor 
    public Person()
    {
    }
 
    private string _Name;
    public string Name
    {
        //set the person name
        set { this._Name = value; }
        //get the person name 
        get { return this._Name; }
    }
}
-------------------------------------------------

You can simulate this functionality in PHP 5.x using the magic __get () and __set () functions, but that solution has one big drawback. Magic variables are not visible in the PHP code (in a class declaration), and in IDE applications (until the variable is declared “virtually” from the phpDoc comments).

Because of that I present you another little-known functionality of the PHP language, which solves the above problems. In my solution you can easily convert class properties into magic variables which will be visible everywhere in the code/IDE applications.

The official PHP documentation suggests that there is no way to trigger magic methods in case of operations performed on declared class properties (the __get (), __isset (), __unset () and __set () methods operate only on variables that were not declared in the given class).

But the reality is different. Looking at the source code of PHP interpreter one can quickly notice that the PHP documentation is somewhat incomplete. There is one, the only way to force the PHP interpreter to use magic methods on the declared class properties. You can trigger this functionality during the construction of an object.

Below is a sample script which enumerates through all of the properties and switches them to read-only mode if their name starts with an underscore:

-------------------------------------------------
class Test
{
	public $_magic = "readonly";
 
	protected $realMagic = array();
 
	public function __construct() {
		foreach($this as $name => $value) {
			if($name[0] === '_') {
				$this->realMagic[$name] = $value;
				unset($this->$name);
			}
		}
	}
 
	public function __get($name) {
		if(isset($this->realMagic[$name])) {
			return $this->realMagic[$name];
		}
	}
 
	public function __set($name, $value) {
		if(isset($this->realMagic[$name])) {
			throw new Exception('This property is read only');
		}
	}
}
-------------------------------------------------

Let’s make a test with a code below:
-------------------------------------------------
$x = new Test();
 
echo "<br>READING _magic PROPERTY... ";
 
echo $x->_magic;
 
echo "<br>SETTING _magic PROPERTY...<br>";
 
$x->_magic = "test";

…and see the results:

READING _magic PROPERTY... readonly
SETTING _magic PROPERTY...
 
Fatal error: Uncaught exception 'Exception' with message 'This property is read only' in C:\Documents and Settings\agraniszewski\Desktop\www\example2.php:26 Stack trace: #0 C:\Documents and Settings\agraniszewski\Desktop\www\example2.php(39): Test->__set('_magic', 'test') #1 {main} thrown in C:\Documents and Settings\agraniszewski\Desktop\www\example2.php on line 26
-------------------------------------------------

SUMMARY

The greatest advantage of this solution is that we can thus simulate static/magic properties in PHP without sacrificing the intellisense functionality of any popular IDE application.
  Files folder image Files  
File Role Description
Plain text file magic.php Class Library
Accessible without login Plain text file read_only_property.php Example Example: marks all properties with an underscore as the first letter of their names as a read-only
Accessible without login Plain text file readme.txt Doc. Documentation

 Version Control Unique User Downloads Download Rankings  
 0%
Total:539
This week:1
All time:5,299
This week:1,047Up
User Comments (1)
interesting theoretical approach
5 years ago (Grigori Kochanov)
67%StarStarStarStar