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

Dynamic Model Creation inside a User Model Not working for some reason with Namespaces

I am trying to create dynimic model class with a model function inside the user model, however for some reason it unable to identify the class location. it gives me an error

Fatal error: Class 'VarEducation' not found

    public function partner()
{
    $view_service=new ViewService();
    $partner_vars_check=$view_service->getUserVarPartnerModelCheckMappingArray();
    foreach($partner_vars_check as $partner_key=>$partner_var){
        $table= str_replace("p_","var_",$partner_key);
        $sql = "SELECT * FROM ".$table."
                WHERE id='" . $this->{$partner_key} . "'
                ORDER BY id DESC";
        $partner_obj = new $partner_var();
        $this->{$partner_key} = new \Phalcon\Mvc\Model\Resultset\Simple(null, $partner_obj,
            $partner_obj->getReadConnection()->query($sql));
    }

Any idea on what causing this ? i suspect the namespace but this dynamic models all are inthat model name space.



85.5k

did you register your namespace ?


$loader = new Loader();

$loader->registerNamespaces([
    "myApp\Models"        => MODELS_DIR . DS .'models' . DS,
]);

$loader->register();


13.4k

Yes i did actually instead of the $var, if i use the String class name it works perfectly, only the $var is used it causing probelms for some unknown reason.

for example this work fine

$partner_obj = new VarEducation();



85.5k

can you print_r $partner_vars_check please



13.4k

function is as below

public function getUserVarPartnerModelCheckMappingArray() { return array( 'p_education' => 'VarEducation', 'p_body' => 'VarBody', 'p_ethnicity' => 'VarEthnicity', 'p_religion' => 'VarReligion', 'p_family' => 'VarFamily', 'p_career' => 'VarCareer', 'p_smoking' => 'VarSmoking', 'p_drinking' => 'VarDrinking', 'p_status' => 'VarStatus', ); }

can you print_r $partner_vars_check please



85.5k
edited Nov '15

this works fine, so it has to be the loader.

maybe you forgot the namespace ?

$arr  = array(
        'p_education' => 'VarEducation'
);

class VarEducation {
    public function koko(){
        return 'koko';
    }
};

foreach($arr as $partner_key=>$partner_var){

    $partner_obj = new $partner_var();

    print_r($partner_obj);
}


13.4k
edited Nov '15

but how can it works if its just new VarEducation() as text that doesn't need any namespace.. strange isn't it ? should check it indepth the logic



85.5k

what will happen if you try

'p_education' => '\VarEducation'

but i am not sure its allowed syntax