sdexp
sdexp

Reputation: 776

Calling a class from within another class PHP7

I have an abstract class with all the common stuff in it (DB connections etc) and I could put the banners in there but I wanted them separate from the DB in their own class. This is what I have that works...

include "includes/abstract-class.php";
include "includes/extended-class.php";
include "includes/separate-class.php";

$separate = new SEPARATEClass();
$extended = new EXTENDEDClass($separate);

Then, in the abstract class...

abstract class ABSTRACTClass 
{

    public function __construct (SEPARATEClass $separate){
        $this->separate = $separate;
    }

    // This empty function is needed in order for there not to be fatal errors 
    // even though the function with the same name that actually has content is 
    // in the separate class...
    protected function draw_small_banner(){
    }

Then, in the extended class where I want to call the functions I can do something like this that calls the draw_small_banner() function from SEPARATEClass()...

class EXTENDEDClass extends ABSTRACTClass 
{

    parent::draw_small_banner();

I tried a few different ways of doing this from some other Stackoverflow questions but this was the only way I could get it to work. This is using PHP 7. Is there a better way that will work?

Also, it seems odd to me that this will only work if the empty functions are in the abstract class. If anyone can explain this or suggest a neater alternative I'd be very grateful.

Thanks.

Upvotes: 0

Views: 89

Answers (1)

Phil
Phil

Reputation: 165065

As mentioned in the comments, anything that extends ABSTRACTClass and doesn't omit its constructor should have access to $this->separate.

Assuming SEPARATEClass has something like

public function draw_small_banner() {
    // do some drawing or something
}

I would first make it a protected member of ABSTRACTClass...

abstract class ABSTRACTClass {
    protected $separate;

    public function __construct(SEPARATEClass $separate) {
        $this->separate = $separate;
    }
}

then, in your extending classes, you should have access to it

class EXTENDEDClass extends ABSTRACTClass {
    public function drawStuff() {
        $this->separate->draw_small_banner();
    }
}

Execution would look like

$separate = new SEPARATEClass();
$extended = new EXTENDEDClass($separate);
$extended->drawStuff();

Upvotes: 3

Related Questions