0

There are similar questions but none that are giving me a satisfactory answer.

First off, here's my (simplified) code:

class classA; {
  function __construct() {
    ...do something...
    $this->init();
  }
}

class classB extends classA {
  function init {
    ...do something specific to this class which has to be done in the constructor...
  }
}

When I call a new instance of the child function, the line "$this->init();" triggers the following error in the Apache error log:

[error] [client ip] PHP Parse error: syntax error, unexpected T_STRING, 
expecting T_FUNCTION in ... on line... referrer:...

My reasoning is that I have things that I need to do in the constructor of the child class but I can't have a constructor there otherwise the constructor of the parent won't be processed. So I create the child, which pulls in the functions from the parent and executes the __constructor function. This function calls the (child's) init() function which has the child-specific logic and continues execution.

My only guess is that it's calling a function that isn't read into memory yet - but I thought PHP read the entire file into memory before execution of the __constructor function. I've looked to see if there's a preload function but haven't found anything other than doing an include statement - but I feel this is the wrong track.

Any help is greatly appreciated!

EDIT: touching up some irrelevant details.

2
  • The Parse error comes when I call the init function and I can't figure out why, hence my question. I'll add this detail to my post. Thanks! edit-also touched up the __construct(or) typo. Commented Apr 6, 2014 at 11:06
  • Try declare init() method in the parent class as abstract Commented Apr 6, 2014 at 11:11

1 Answer 1

2

Within your child class call the parents constructor

   class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! This is much more elegant than I thought it would be. I'll plug this in today and let you know how it turned out.
great - glad to help it is much better to ensure that parent classes know nothing of children.

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.