I have two classes, class A and class B, i am trying to access class B through a function in class A.
At the moment i am able to do this by creating a new instance of class B inside of the function in class A, but i want to know if there is a way to do this without creating a new instance of class B inside of class A.
Here is an example of what i would want to do:
class a{
function a(){
return $this->b();
}
}
class b extends a{
function b(){
return "It Works!";
}
}
$doIt = new a();
echo $doIt->a();
From your comment:
Basically i have class B that works with the database, and class A that connects the users actions on the site to class B. So user does something->class A starts working->Passes info on to class B to add to the database. It did seem that this is not all that possible, but i know there are people with a lot more knowledge than I have so i wanted to see if anyone else knew of some way to do this.
As you describe: B
works with the database, A
performs actions (requested by the user). B
sounds like some sort of mapper/data access object, while A
sounds like a service (I'll refer to BMapper
and AService
to be more deliberate).
What you've outlined indicates you are not using PHP inheritance correctly. Inheritance represents "is a" relationships. (Image
is a Media
, PathMover
is an Animator
, etc...). While @Malcolm's answer technically works, it is not for your scenario.
In OOP we would say that BMapper
is a dependency of AService
. Thus whenever we are calling a method in AService
, we would expect it to depend on an instance of BMapper
. This relationship is satisfied typically through dependency injection (see: What is dependency injection?).
<?php
class AService {
private $bMapper;
public function __construct(BMapper $bMapper)
{
$this->bMapper = $bMapper;
}
public function doAction()
{
return $this->bMapper->performSomethingInDatabase();
}
}
class BMapper {
public function performSomethingInDatabase()
{
/**
* ..whatever
*/
}
}
$service = new AService(new BMapper);
$service->doAction();
You can see that we've defined our dependent class's dependency in its constructor, to be satisfied by whoever/whatever is using that class.