Can we create an object of a class inside another class in php?

class, object, php

Solution

Yes you can, but that increases code coupling and makes testing harder. I'd suggest creating it outside the class and pass it as an argument (it is called Dependency Injection).

class Foo
{
}

class Bar
{
  public function __construct(Foo $foo)
  {
    $this->foo = $foo;
  }
}

$foo = new Foo();
$bar = new Bar($foo);

Problem

Can we create an object of a class inside another class in php?I hav made a small application in php,now I am trying to convert the entire code in a class-methods-object fashion.I m now Confused.

Original source