Getter without property?

Possible to have a getter without a backing property?

edited Jun '16

Yes, why not ?

But why you even wanna do it ?



3.7k

I've tried and it hasn't worked unless the property exists.

Why why why? :)

I want getters for transformations of properties. Here is a contrived example:

protected $arr;

public function getArrKeysReversed() {

        $keys = array_keys($this->arr);
        rsort($keys);
        return $keys;
}
edited Jun '16

But wait - if you want to access property then obviously you need to create it. I just didn't understand your question. You can create getter where you DON'T access property.



3.7k

OK. I'll try again. It isn't finding by getters via propery syntax: $this->arrKeysReversed, which is what I want.

edited Jun '16

I don't understand. If you want to access property then you need to add it.....

Also it's not related to phalcon framework.

Whenever a property is accessed that doesn't actually exist, PHP calls the object's __get() method. If your object is extending \Phalcon\Mvc\Model, you'll need to ensure you call parent::__get() too. Something like:

public method __get($name){
    if($name == 'arrKeysReversed'){
        $keys = array_keys($this->arr);
        rsort($keys);
        return $keys;
    }
    else{
        return parent::__get($name);
    }
}


3.7k

That was the missing piece. Thank you!

You shouldn't really use it. Just create normaller getter method and/or property bro.