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 constructo
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.
This is possible in PHP 7 with Anonymous classes.
See the example from the docs:
class Outer
{
private $prop = 1;
protected $prop2 = 2;
protected function func1()
{
return 3;
}
public function func2()
{
return new class($this->prop) extends Outer {
private $prop3;
public function __construct($prop)
{
$this->prop3 = $prop;
}
public function func3()
{
return $this->prop2 + $this->prop3 + $this->func1();
}
};
}
}
echo (new Outer)->func2()->func3();
// Output: 6
This is a simple example showing usage of anonymous classes, but not from within a class:
// Pre PHP 7 code
class Logger
{
public function log($msg)
{
echo $msg;
}
}
$util->setLogger(new Logger());
// PHP 7+ code
$util->setLogger(new class {
public function log($msg)
{
echo $msg;
}
});