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.



61.2k

did you register your namespace ?

$loader = new Loader();

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

$loader->register();


4.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();



61.2k

can you print_r $partner_vars_check please



4.4k

function is as below

public function getUserVarPartnerModelCheckMappingArray() { return array( 'peducation' => 'VarEducation', 'pbody' => 'VarBody', 'pethnicity' => 'VarEthnicity', 'preligion' => 'VarReligion', 'pfamily' => 'VarFamily', 'pcareer' => 'VarCareer', 'psmoking' => 'VarSmoking', 'pdrinking' => 'VarDrinking', 'p_status' => 'VarStatus', ); }

can you print_r $partner_vars_check please



61.2k
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);
}


4.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



61.2k

what will happen if you try

'p_education' => '\VarEducation'

but i am not sure its allowed syntax