Use / change property of an extended class and print by instance

1

Example scenario

Root folder

  • ClassA.php
  • ClasseB.php
  • index.php

File: classeA.php

class ClasseA 
{
    public $retorno = null;
    public $error   = "Erro desconhecido";

    function __construct
    {
       $this -> func_A();
    }

    public function func_A()
    {
        require_once 'classeB.php';
        $obj = new ClasseB;
        $obj -> func_B();
    }

}

File: classeB.php

class ClasseB extends ClasseA
{
    public function func_B()
    {
       $this -> error = "Erro em func_B";
    }

}

File: index.php

require_once 'ClasseA.php';

$obj = new ClasseA;
echo ($obj -> retorno != null) ? $obj -> retorno : $obj -> error;

Problem

My return from index.php is: "Unknown error".

What I expected: "Error in func_B".

Doubt

  • Why does error property of ClasseA not change?
  • What possible solutions?
asked by anonymous 05.12.2018 / 13:31

2 answers

4

I admit that I may be wrong because PHP usually has weird behavior, I will respond to the universal logic I know, even because I can not reproduce it because I only have PHP in these online loop with such a construction as you need for them.

You are creating a totally different object within func_A() , even if it is derived from ClasseA , this object stored in $obj within func_A() is not the same object that is operating in ClasseA . When you use $this in the ClasseB object, that is, $obj , you are not changing $this of $obj global, they are very different objects, and what you are getting printed is this object only.

Remembering that% class internal% exists only as long as an object of this class exists, but it is completely separate, only has a #

The fact that two completely different variables have the name may have hampered understanding.

This scenario is atypical, and I doubt if it has real usefulness, but if you are wanting to do something real, it seems to be wrong engineering and the path should be quite different from this tempted.

    
05.12.2018 / 13:52
1

It's not exactly what you were trying to do, but maybe it might help you:

class ClasseA
{
    public $retorno = null;
    protected $error = "Erro desconhecido";

    public function __get($name)
    {
        require_once 'ClasseB.php';
        $obj = new ClasseB;
        $obj->func_B();

        return $obj->$name;
    }
}

In addition, I'm not sure what the utility of calling classA or instead of directly instantiating classB (since it extends to A). The error in your code (as best explained by Maniero) is that the $ obj variable only exists within the context of the calling function and does not override the attributes of the class.

Now, using the magic function __ get , you can override the non-public methods call.

    
05.12.2018 / 14:20