-1

I am using this name space

use \App\Model\PostsModel;

and i am trying to access the class like this in another class :

public $model = PostsModel::class;

the out put of vardump is "App\Model\PostsModel" and vardump shows that the type of it is string.

I have searched a lot, but I couldn't find how to cast/convert string into stdclass. This is what I have tried:

$model = \App\Model\PostsModel;

I also tried to get a instance of it

public $model = new \App\Model\PostsModel;  
public $model = new PostsModel::class; 

My vardump is:

vardump($this->model);

which shows that my namespace addresses are correct

Robert
  • 7,394
  • 40
  • 45
  • 64
Iman Emadi
  • 421
  • 4
  • 14

1 Answers1

1

The problem is you are trying to access the class without instantiating before.

The value from ClassName::classis always a string, not an instance of that class.

You can assign the class name (string) to a var and then create a new instance of the class just using that variable. See the next example.

<?php

use \App\Model\PostsModel;

class OtherClass {
    public $model;

    public function callOther() {
        $this->model = PostsModel::class;

        $instance = new $this->model();
        $instance->callSomeMethod();
    }
}
manuerumx
  • 1,230
  • 14
  • 28
  • thank you ,my problem solved with the way you said , but i had tried $this->model = new PostsModel::class ; why this way doesn't work ? aren't these same thing ? – Iman Emadi Feb 10 '19 at 13:38
  • @ImanEmadi as i said the problem is `ClassName::class` or in this case `PostsModel` is returning the namespace and name of the class as string. The best way to create a new class instance is calling directly without the class. `$this->model = new PostsModel();` See the example 3 in http://php.net/manual/en/language.oop5.constants.php – manuerumx Feb 10 '19 at 20:43
  • Look this question/answers https://stackoverflow.com/questions/4578335/creating-php-class-instance-with-a-string – manuerumx Feb 10 '19 at 20:50