My PHP class constructor appears to not be getting called when the class is initiated. This is what my constructor looks like:
public function __contruct()
{
$GLOBALS['page_content'] .= "<p>Constructor entered.</p>\r\n";
try
{
$this->ConstructorBase();
}
catch ( Exception $e )
{
throw new Exception(
"Error in ".__FILE__."(".__LINE__."): Constructor failed.",
CLoginError::ERROR_CANNOT_INSTANTIATE, $e );
}
}
Later in the same file, in the global scope, I attempt to instantiate the class:
$Login = new CLogin();
However, when I inspect $GLOBALS['page_content']
, after instantiating the class, it is empty, as if the constructor was never called. What is odd is that I can call public member functions. If you want to see it, the full source is posted here:
http://pastebin.com/D95YnUmS
It is defined inside the class and is used to automatically call when the object is created. PHP4 provides the constructor method whereas PHP5 provides the magic method __construct and __destruct. This method is automatically called when an object is created or destroyed.
PHP - The __construct Function A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();
You named your function __contruct()
where it should be __construct()
. This is a very common error, you should probably get some sleep.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With