开发者

PHP autloading variable

I am not sure if this possible or if this is the right place to post this type of questions but here goes!

Is there any way开发者_开发百科 to autoload a variable with a class of the same name? An example of this:

class MyClass
{
    ....
    function display() { echo 'test'; }
}

I am wondering if it is possible to do the following:

$MyClass->display();

without previously creating an instance of the MyClass class within the $MyClass variable.

As I say I am not sure if this is possible and if this is not the right place for this kind of question I will happily delete my post.

UPDATE Thanks for all your responses guys, the more I thought about and after reading your comments I realised it just wasn't a good idea and really wouldn't be practical.

Thanks


I think you should take a different approach, and use a static method.

class MyClass
{
    ....
    static function display() { echo 'test'; }
}

MyClass::display();

You can only do this with functions that act the same no matter what instance of the class. Your example is a static method, because the function will always return test. If the function had to use instance variables or methods, then you cannot use this.


I think you want an static class/function. You could do MyClass::display();.


What you can do is make your method static and call the method directly on the class:

class MyClass
{
    public static function display() { echo 'test'; }
}

MyClass::display();

Apart from that: "Autoloading" variables is not possible.


Make it a static method. You don't need to create an instance of the class to invoke a static method.

class foo {
    private static $test;

    public static function test() {
        echo 'test';
    }
}

And then invoke it as:

foo::test();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜