Patrick
Patrick

Reputation: 4905

php extending but with a new constructor...possible?

I have a class:

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

what I would like to do is a have a class that sort of extends the test class. I say 'sort of', because the class needs to be able to run whatever function the test class is able to run, but NOT run the construct unless I ask it to. I do not want to override the construct. Anyone has any idea how to achieve this?

Upvotes: 3

Views: 3055

Answers (3)

Adrian
Adrian

Reputation: 1402

You could define a "preConstructor" method in your sub-classes that your root-class constructor would execute, and use a boolean flag to determine whether constructor code should be executed.

Like so:

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;
    }
}

Upvotes: 0

St. John Johnson
St. John Johnson

Reputation: 6660

What's wrong with overriding the construct?

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

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

Upvotes: 1

Amy B
Amy B

Reputation: 17977

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


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

Upvotes: 5

Related Questions