Henrik Petterson
Henrik Petterson

Reputation: 7094

Using include in class properly

I have a main class in index.php:

class myClass {

    public function lorem() {
        include_once 'extendClass.php';
    }

    public function __construct() {
        $this->lorem();
    }

}

// run class
new extendClass();

I need to include_once 'extendClass.php' within the lorem() function.

In my extendClass.php file, I extend the class function with:

class extendClass extends myClass {

    public function lorem(){
        echo "foo bar";
        parent::lorem();

    }

}

When I use new extendClass() in index.php, I get an error because the include_once() is not triggered. What's the solution to this puzzle?

Note: include_once() must be within myClass.

Upvotes: 1

Views: 31

Answers (1)

Machavity
Machavity

Reputation: 31614

There's two problems here

  1. You're creating a child class that's overwriting the lorem() function. You would have to explicitly call parent::lorem() to get to it
  2. Even if you call it, that parent function doing the include means that anything defined in that function is locally scoped to that function. So that means your child function can't inherit it (at least not without some sort of return declaration)

You need to move the include outside your class declaration

include_once 'extendClass.php';
class myClass {

    public function lorem() {
    }

    public function __construct() {
        $this->lorem();
    }

}

// run class
new extendClass();

Upvotes: 3

Related Questions