Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiating a class without assigning to a variable

Tags:

php

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
like image 485
Samuel Fullman Avatar asked Jul 09 '14 12:07

Samuel Fullman


People also ask

Can you instantiate a class in itself?

so by line 1, class is both loaded and initialized and hence there is no problem in instantiating an instance of class in itself.

What is instantiating a class?

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.

Can object class be instantiated directly?

You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)

What does instantiating a class mean Python?

Instantiating a class is creating a copy of the class which inherits all class variables and methods. Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines.


1 Answers

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();
like image 175
deceze Avatar answered Oct 12 '22 08:10

deceze