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

Using `settype` on fields breaks model permanently

I recently upgraded my PHP server to 7.0 and added type enforcements in lots of my classes. Using the built in model event afterFetch() I forced my model to automatically change the type of certain fields after fetching a record using the built in PHP settype function.

This however, caused all of my models to break when calling any save() functions on existing methods. This is an example of my code:

Example of my model:

class Books extends \Phalcon\Mvc\Model
{
    public $id;
    public $read;
    public $title;

    public function initialize()
    {
        $this->setSource('Books');
    }

    public function getSource()
    {
        return 'Books';
    }

    public function afterFetch()
    {
        settype($this->id, "int");
        settype($this->read, "bool");
    }
}

Using my code:

$book = Books::findFirst(10);
$book->save();

if ($messages = $book->getMessages())
{
    foreach($messages as $message)
    {
        echo "$message<br />";
    }
}

This results in the following output:

id is required
read is required

Does anyone know why this happens and if so how I could fix this? I'm currently using version 2.1.0r. Thanks

Can you check var_dump($book); before $book->save(); if those properties exist ? After removing this settype it works, right ?

Simply writing my code like this fixed my issue:

$this->id = (int) $this->id;

Thanks for the help though (calling var_dump caused too much output to even read)

Can you check var_dump($book); before $book->save(); if those properties exist ? After removing this settype it works, right ?