James Bell
James Bell

Reputation: 614

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

Upvotes: 2

Views: 80

Answers (4)

NikiC
NikiC

Reputation: 101946

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.

Upvotes: 0

Casey Flynn
Casey Flynn

Reputation: 14048

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

Upvotes: 0

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14951

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

Upvotes: 1

Brad
Brad

Reputation: 163528

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.

Upvotes: 2

Related Questions