I was wondering if it is allowed to create an instance of a class inside another class.
Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.
Example (a database class):
class some{ if(.....){ include SITE_ROOT . 'applicatie/' . 'db.class.php'; $db=new db
Yes you definitely can instantiate a class inside a constructor method of another class.
PHP 7 has introduced a new class feature called the Anonymous Class which will allow us to create objects without the need to name them. Anonymous classes can be nested, i.e. defined inside other classes. Read this article to learn how to defined and use anonymous classes nested inside other classes.
The public keyword is used in the definition of the class, not in a method of the class. In php, you don't even need to declare the member variable in the class, you can just do $this->tasks=new tasks() and it gets added for you.
Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.
You can't define a class in another class. You should include files with other classes outside of the class. In your case, that will give you two top-level classes db
and some
. Now in the constructor of some
you can decide to create an instance of db
. For example:
include SITE_ROOT . 'applicatie/' . 'db.class.php'; class some { public function __construct() { if (...) { $this->db = new db; } } }
People saying that it is possible to 'create a class within a class' seem to mean that it is possible to create an object / instance within a class. I have not seen an example of an actual class definition within another class definition, which would look like:
class myClass{ class myNestedClass{ } } /* THIS IS NOT ALLOWED AND SO IT WON'T WORK */
Since the question was 'is it possible to create a class inside another class', I can now only assume that it is NOT possible.
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