Henrik Petterson
Henrik Petterson

Reputation: 7094

Run class construct without creating an object

I have a class setup like this:

class myClass {
    public function __construct() {
        echo 'foo bar';
    }
}

To run it, I can simply do:

$object = new myClass;

Is there any way to run the class so __construct initiates without creating a new variable with the class object.

For example, a basic function can be run with:

functionname();

Upvotes: 1

Views: 2232

Answers (3)

PiotrCh
PiotrCh

Reputation: 103

You can try something like this if you want to avoid static:

(new MyClass)->myFunction();

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40886

Don't call __construct directly. If you need something in the constructor to occur but you don't want an object created as a result, then use a static method.

class Thing{
    public static function talk(){echo "I talk";}
}
Thing::talk(); // 'I talk'

Static methods can be called without the need for an object instance of the class.

__construct is part of a special group of methods in PHP, called Magic Methods. You don't call these directly, but PHP will call them when some event occurs. For instance when you call new on a class, __construct is executed.

Another example: if you try to get a property that doesn't exist, __get will be executed (if found):

Class Thing{
    public property $name = 'Berry';
    public function __get($propertyName){
        return "$propertyName does not exist!";
    }
}
$t = new Thing();
echo $t->name; // 'Berry'
echo $t->weight; // 'weight does not exist!';

Upvotes: 4

zajonc
zajonc

Reputation: 1971

I have no idea why you need this but you don't need to create a variable. You can just create object without store it anywhere.

class myClass {
    public function __construct() {
        echo 'foo bar';
    }
}

new myClass();

In this case only the constructor will be call.

Upvotes: 1

Related Questions