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
so by line 1, class is both loaded and initialized and hence there is no problem in instantiating an instance of class in itself.
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.
You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With