user2219645
user2219645

Reputation:

PHP unassigned class instance?

I've noticed that PHP seems to allow the following:

<?php

class StandAlone {
    public function __construct() {
        echo "I am constructed!";
    }

    public function __destruct() {
        echo "I am destructed!";
    }
}

new StandAlone;

without any fuss.

Is this an error in that PHP should be raising an error? Or is this allowable and the class instance just exist out in memory somewhere, with no way to directly access that particular instance?

Upvotes: 4

Views: 132

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270677

The class instance does not need to be stored in a variable. You could, for example, pass it as a parameter to a function that accepts a StandAlone object as its parameter. It exists in memory for the amount of time during the script execution that it is in use. If never assigned, it is constructed, destructed, and freed.

call_a_function(new StandAlone);

I cannot think of any practical situation where you would call new Object without assigning it or passing to a function that wouldn't be better served by just defining a function to do some work instead of a class, however.

Upvotes: 1

genesis
genesis

Reputation: 50974

It works fine for me

http://sandbox.phpcode.eu/g/b9d04.php

Upvotes: 0

Related Questions