Call a Class Inside Another Class in PHP
A common stumbling block for developers transitioning into object-oriented PHP is understanding how to instantiate child classes from within parent class methods. The specific scenario you encounteredâdeclaring a property, then attempting to instantiate a new class inside a method using that same propertyâis a classic pattern that often trips people up due to scoping rules and property visibility.
In your example, the error stems primarily from two distinct issues: the declaration of $this->tasks inside the validate() method versus outside it, and the attempt to pass $this as a constructor argument without defining that capability in the child class.
Property Visibility and Initialization Scope
The most immediate fix involves moving the property declaration out of the function body. In PHP, you cannot declare a public property like public $tasks; inside a method and expect it to persist or behave as intended if you haven't established its type or existence beforehand. Furthermore, while you can assign a new instance to an already declared property inside a method, declaring the property inside the method makes it a local variable for that specific execution context unless you explicitly declare it as public or private at the class level first.
To resolve this, move the property declaration to the top of the admin class:
class admin
{
public $tasks;
function validate()
{
if (!$_SESSION['level'] == 7) {
barMsg('YOU\'RE NOT ADMIN', 0);
return FALSE;
} else {
// Now we can safely assign the new instance here
$this->tasks = new tasks();
$this->tasks->test();
$this->showPanel();
}
}
}
By defining public $tasks at the class level, you ensure that every instance of admin has a slot to hold its own tasks object. Assigning the new instance inside the method is perfectly valid and standard practice for lazy initialization.
Constructor Dependency Injection
The second hurdle in your original code was passing $this as an argument: new tasks($this). This syntax implies that the tasks class expects a dependencyâin this case, an instance of the admin classâto be injected into its constructor. However, your tasks class definition showed an empty constructor:
class tasks
{
function test()
{
echo 'test';
}
}
If you attempt to instantiate a class with arguments when the constructor accepts none, PHP throws a fatal error regarding an incorrect number of arguments. To make tasks accept $this, you must define the constructor and match the parameter types:
class tasks
{
private $admin;
public function __construct($admin)
{
$this->admin = $admin;
}
public function test()
{
echo 'test';
}
}
Once the constructor is defined to accept $admin, your original instantiation line new tasks($this) will work correctly. This pattern is known as dependency injection, where the parent class provides its own instance to the child class. This allows the tasks object to potentially access properties or methods on the $admin object later within its lifecycle.
When to Use Dependency Injection
There is a trade-off involved in passing $this to a new class. While it works well for tightly coupled components, it can make unit testing difficult if you want to mock the admin dependency later. If you find yourself frequently needing to pass the current object instance to other classes, consider whether that coupling is necessary or if you should rely on service containers instead.
For example, in a Laravel application, you would typically define these relationships in your Service Providers rather than manually instantiating them inside business logic methods. You can explore how dependency injection is handled more robustly in modern PHP frameworks at LaravelCompany. They often use service containers to resolve these dependencies automatically, removing the need for manual instantiation and reducing the risk of passing incorrect object states.
Ultimately, ensuring your property declarations exist at the class level and that your constructors match their expected arguments is the key to avoiding runtime errors when calling classes from within others.