'instantiating a class without assigning to a variable
I have a need to call a class which will perform actions but which I know I will not be calling the methods of. This is a PHP application. Does anyone ever just do the following:
require('class.Monkeys.php');
new Monkeys(); //note I didn't assign it to a variable
Solution 1:[1]
Yes, that's perfectly valid. However, it is arguably bad form, because the golden rule is that:
Constructors should not do actual work.
A constructor should set up an object so that it is valid and in a "ready state". The constructor should not start to perform work on its own. As such, this would be saner:
$monkeys = new Monkeys;
$monkeys->goWild();
Or, if you prefer and are running a sufficiently advanced PHP version:
(new Monkeys)->goWild();
Solution 2:[2]
Well let just say that we have a classname called Monkeys.
File class.Monkeys.php
class Monkeys {
function __construct()
{
$this->doSomething()
}
public function doSomething(){
echo "new Monkeys()->doSomething() was called";
}
public function anotherMethod(){
echo "new Monkeys()->anotherMethod() was called";
}
}
Now you can instantiate the class on runtime without saving it into a variable.
require('class.Monkeys.php');
// you can just instantiate it and the constructur will be called automatically
(new Monkeys());
// or you can instantiate it and call other methods
(new Monkeys())->anotherMethod();
I'm not sure if the garbage collector will delete the instantiated classes or not, but i assume since those classes are not saved into a variable this would not be saved somewhere in the memory and that would be perfect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | deceze |
| Solution 2 |
