Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Setters/Getters doesn't worker

I try a code like example:http://docs.phalconphp.com/zh/latest/reference/models.html#setters-getters-public-properties-vs-setters-getters

class Robots extends \Phalcon\Mvc\Model

{

protected $id;

public function getId(){

    return 2;

}

}

but it does't worker

$robot = Robots::findById(1);

echo $robot->id; // it's 1

my phalcon version is 1.3.4

edited Feb '15

Not problem with Phalcon, in your example, you'll need $robot->getId()

protected $id;

public function __get($name)
{
    if (method_exists($this, $name)) {
        return $this->$name;
    }
}

// This can be accessed with $robot->id;


450
edited Feb '15

so, the phalcon doesn't implement those actions using it's get getId() or setId()?

like: i have a

public function setId($id){
    return $this->id = 2;
}

then

$robot = new Rebots();
$robot->id = 1;
$robot->save();

the id column in db is still 1?



3.8k
Accepted
answer
edited Feb '15

Nope, Phalcon doesn't create the accessors for you, $robot->id = 2 is not same as $robot->setId(2), this is really related PHP OO and not Phalcon.

if you have public function setId($id) { ... } for protected property (class variable), you then have to set that property like $robot->setId(2).

In the Phalcon examples, public class variables is used, or you can use protected class variables with magic method accessors. See __get() and __set() here : http://php.net/manual/en/language.oop5.magic.php

Here is my set magic method.

    /*
     * Checks if property exists
     * Changes $this->camelCase to $this->camel_case, due to my DB naming convention
     * omited this on my __get example above
     */
    public function __set($name, $value)
    {
        if (!property_exists($this, $name)) {
            $name = preg_replace_callback('/[A-Z]/', function($matches) {
                    return '_' . strtolower($matches[0]);
            }, $name);
        }
        $this->$name = $value;
    }


450

well, thx