Question

Using PHP, how do I define/declare getter and setter methods/functions as part of the declaration of a property in a class?

What I'm trying to do is specify the getter and setter methods as part of a property, instead of declaring separate set_propertyName($value) and get_propertyName() functions/methods.

What I've got:

class my_entity {
    protected $is_new;
    protected $eid; // entity ID for an existing entity
    public function __construct($is_new = FALSE, $eid = 0) {
        $this->is_new = $is_new;
        if ($eid > 0) {
            $this->set_eid($eid);
        }
    }

    // setter method
    public function set_eid($eid) {
        $is_set = FALSE;
        if (is_numeric($eid)) {
            $this->eid = intval($eid);
            $is_set = TRUE;
        }
        return $is_set;
    }
}

What I want (without making $this->eid an object):

class my_entity {
    protected $is_new;
    // entity ID for an existing entity
    protected $eid {
      set: function($value) {
        $is_set = FALSE;
        if (is_numeric($value)) {
            $this->eid = intval($value);
            $is_set = TRUE;
        }
        return $is_set;

      }, // end setter

    }; 
    public function __construct($is_new = FALSE, $eid = 0) {
        $this->is_new = $is_new;
        if ($eid > 0) {
            $this->set_eid($eid);
        }
    }

    // setter method/function removed
}
Was it helpful?

Solution 2

This was proposed for PHP 5.5, but the vote failed to get the necessary 2/3 majority required to accept it into core, so it won't be implemented (despite the code to implement that change having been submitted).

It's entirely possible (with the plethora of new PHP engines and Hacklang currently appearing) that it will be resubmitted at a future time, especially if Hacklang decides to implement it; but for the moment the option of using C# getters/setters isn't available in PHP

OTHER TIPS

PHP only allows one getter and one setter function per class, they are the __get & __set magic methods. These two magic methods must handle get and set requests for all private/inaccessible properties. http://www.php.net/manual/en/language.oop5.magic.php

private function set_eid($id)
{
    //set it...
    $this->eid = $id;
}

private function get_eid($id)
{
    //return it...
    return $this->eid;
}

public function __set($name, $value)
{
    switch($name)
    {
        case 'eid':
            $this->set_eid($value);
        break;
    }
}

public function __get($name)
{
    switch($name)
    {
        case 'eid':
            return $this->get_eid();
        break;
    }
}

In the 2 switch statements you could also add the names of other properties.

It's important to remember that __get and __set are only called if the variable is inaccessible, this means that when getting or setting from inside the class you will still have to manually call set__eid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top