Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Constructor Not Called Upon Instantiation [closed]

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

like image 780
Jim Fell Avatar asked Jan 04 '12 20:01

Jim Fell


People also ask

What are the __ construct () and __ destruct () methods in a PHP class?

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.

How do you call a constructor in PHP?

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 (__)!

What is parent __construct?

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".

How can we call a constructor from parent class in PHP?

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();


1 Answers

You named your function __contruct() where it should be __construct(). This is a very common error, you should probably get some sleep.

like image 88
Madara's Ghost Avatar answered Nov 11 '22 03:11

Madara's Ghost