Php, but with a new constructor ... maybe?

I have a class:

class test {
    function __construct() {
        print 'hello';
    }
    function func_one() {
        print 'world';
    }
}

what I would like to do is to have a class that extends the test class. I say "kind" because the class must be able to run any function that the test class can perform, but DO NOT run the construct unless I ask for it. I do not want to redefine the design. Does anyone know how to achieve this?

+3
source share
3 answers
class test {
    function __construct() {
        print 'hello';
    }
    function func_one() {
        print 'world';
    }
}


class test_2 extends test {
    function __construct() {
        if (i want to) {
            parent::__construct();
        }
    }
}
+5
source

What happened to redefining the design?

class foo extends test {
   function __construct() { }
}

$bar = new foo(); // Nothing
$bar->func_one(); // prints 'world'
+1
source

"preConstructor" , , , , .

:

class test
{
    protected $executeConstructor;

    public function __construct()
    {
        $this->executeConstructor = true;
        if (method_exists($this, "preConstruct"))
        {
            $this->preConstruct();
        }

        if ($this->executeConstructor == true)
        {
            // regular constructor code
        }
    }
}

public function subTest extends test
{
    public function preConstruct ()
    {
        $ this-> executeConstructor = false;
    }
}
0
source

Source: https://habr.com/ru/post/1739564/


All Articles