Can I instantiate a PHP class inside another class?
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
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.
I just wanted to point out that it is possible to load a class definition dynamically inside another class definition.
Lukas is right that we cannot define a class inside another class, but we can include() or require() them dynamically, since every functions and classes defined in the included file will have a global scope. If you need to load a class or function dynamically, simply include the files in one of the class' functions. You can do this:
function some()
{
require('db.php');
$db = new Db();
...
}
http://php.net/manual/en/function.include.php
It's impossible to create a class in another class in PHP. Creating an object(an instance of a class) in another object is a different thing.
No, it is not possible. Nesting classes and aggregating objects are diffrent mechanisms. Nesting classes means nesting class names, in fact. Class A nested in class B would be named "B\A" (?). From v5.3 you can nest class names (and some other names) in namespaces.