We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Setters/Getters doesn't worker

I try a code like example:https://docs.phalcon.io/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;


822
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?



5.7k
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 : https://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;
    }


822

well, thx