Archive for the ‘.NET’ Category

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

Friday, May 13th, 2011

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. (more…)