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

how I can pass an argument in a model when created instantiate any class?

i want pass values for a model in specific.

for example

in a IndexController


<?php 

class IndexController extends \Phalcon\Mvc\Controller
{
    public function indexAction(){
        $person = new Person('Mary'); // THIS IS MY MODEL
    }


2.8k
Accepted
answer

$item->assign(array(

'colum1' => ...,

'colum2' => ...,

));



17.7k
edited Mar '15

i don't understand.

Is this correct?


<?php 
class IndexController extends \Phalcon\Mvc\Controller
{
    public function indexAction(){
        $person = new Person;
        $person->assign(array('Mary'));
    }

????

I had used onConstruct

<?php 
class IndexController extends \Phalcon\Mvc\Controller
{
    public function indexAction(){
        $person = new Person;
        $person->onConstruct('Mary');
    }

works but I do not know if it's okay

my question is the next this i can you do it?


 $person = new Person('Mary');

Yeah you can initiate the model like that. But inside the model you need to add the onConstruct method that accepts a variable and assigns it to the proper column of model

in Person model

public function onConstruct ($name) { if ($name) { $this->name = $name; } }

This is just one way though. Probably many other.

edited Mar '15

You can solve that by use of oncostruct methods and you can have as many onconstruct methods as you want in your model.

i.e a construct with 2 arguments will execute when you pass 2 parameters on model class instance and so forth for any pairing number of arguments and parameters.