Enzo
Enzo

Reputation: 141

PHP Use child variable to create a class in parent class

I have 3 classes:

  1. Class A - Parent Class
  2. Class B - Child Class
  3. Class C - Class to be used in Class A

I want to use functions from class C using variables from my Child class.

<?php

class A
{
    public function __construct()
    {
        $this->load();
    }

    public function load()
    {
        $class = new C();
        $class->test = $this->test;
        $this->c = $class;
    }
}

class B extends A
{

    public function __construct()
    {
        parent::__construct();
    }
}

class C
{
    public function display()
    {
        echo $this->test;
    }
}

$b = new B();
$b->test = 1;
$b->c->display();

Upvotes: 2

Views: 31

Answers (1)

rjdown
rjdown

Reputation: 9227

Your problem is here:

$class->test = $this->test;

You are attempting to use a property that is not yet defined, because when you do this:

$b->test = 1;

the constructor has already been called, and there's nothing in your classes to update C with the value of B's test property.

You can solve this in a couple of different ways.

1) Send the value in B's constructor, and pass it down the entire chain:

class A
{
    public function __construct($test)
    {
        $this->load($test);
    }

    public function load($test)
    {
        $class = new C();

        $class->test = $test;
        $this->c = $class;
    }
}

class B extends A
{

    public function __construct($test)
    {
        parent::__construct($test);
    }
}

class C
{
    public function display()
    {
        echo $this->test;
    }
}

$b = new B(123);
$b->c->display();

2) Add a method to B that will update C's property:

<?php

class A
{
    public function __construct()
    {
        $this->load();
    }

    public function load()
    {
        $class = new C();
        $this->c = $class;
    }
}

class B extends A
{

    public function __construct()
    {
        parent::__construct();
    }

    public function setTest($test)
    {
        $this->c->test = $test;
    }
}

class C
{
    public function display()
    {
        echo $this->test;
    }
}

$b = new B();
$b->setTest(123);
$b->c->display();

Or perhaps a combination of both.

Upvotes: 1

Related Questions