2

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();

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help. I think I will stick with the first method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.