Henrik Petterson Henrik Petterson - 3 months ago 6x
PHP Question

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
initiates without creating a new variable with the class object.

For example, a basic function can be run with:



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!';