November 26, 2013, 12:05pm
What is the way to create object of class or to use its static methods if I know path to class?
For example I have class with name someClass in
@app\myfolder\someClass.php. What I have to do?
And second question. What I have to do if I know namespace of class?
November 26, 2013, 12:14pm
If root namespace is \app then:
$object = new \app\myfolder\SomeClass();
// static method
$object = new SomeClass();
// static method
when u have this coding in your main.php file…
// autoloading model and component classes
Default you will have those classes automatically…
November 26, 2013, 12:25pm
There’s no need to do any import in Yii2.
November 26, 2013, 12:28pm
If I want to store path to class what I must do?
class myclass extends Object
November 26, 2013, 1:00pm
You will just have to get used to type a bit more with namespaces in Yii2. Don’t try to shorthand everything. This particular thing you are trying to get an answer for cannot be done. Correct usage is as described above.
November 26, 2013, 1:17pm
I have found what I must do:
$myclass = new $string;
Ok. I catch the correct way. But what about aliases? If I have alias ‘
@app/folder/myclass’ only what I have to do to create object?
November 26, 2013, 1:23pm
And what I have to do to use static method of my class?
public function echoit()
echo 'You have done it';
public static function staticMethod()
echo 'It is static method';
Is the correct way?
$string::staticMethod(); //Is it correct?
November 27, 2013, 2:22pm
I have a little investigation about namespaces and aliases in Yii2.
To use class we can use namespaces style.
$result = call_user_func([$myclass, $mymethod]);
But I think we can’t autoload and use classes if we use aliases like
November 28, 2013, 3:49pm
what will happen to the following code?
$obj = new SameNameClass();//which class will be used to create the instance?
November 28, 2013, 5:25pm
PHP doesn’t allow this. You have to alias one of the classes to be something different.
November 29, 2013, 3:19am
got you, qiang!
thank you for answer, and very glad to meet you! I love the Yii framework and I am using it in my work, it is really great! hope you guys keep doing the great job.
btw, a happy thanks giving day to you and the yii team(maybe a little late…) !
December 3, 2013, 1:07pm
Now I’ve found out how use static methods of any class. But I have another question.
How to use ? static property of any class in Yii2
December 4, 2013, 1:48pm
I’ve made another tests
public static $myvar=2013;
public static function getMyVar()
return 'Your var is ' . self::$myvar;
In controller we can do:
echo $myclass::getMyVar(); //For static methods
echo '<br />';
echo $myclass::$myvar; //For static properties
Thanks to Pathfinder and samdark.