Rasmus Olesen DK Rasmus Olesen DK - 5 months ago 24
PHP Question

PHP 5.3 constructor method

I am a Java/C# programmer who is trying to learn/finish a project in PHP.
Can anyone explain to me why "Composition" doesn't work in PHP 5.3 as one would expect from an object oriented language?

I have tried to research the issue, but due to term-confusion (making Google useless...) and bad documentation, I haven't been able to find anything useful yet.

<?php /*PHP VERSION 5.3.3*/

class MyClassOne
{
public function myFunctionOne()
{
echo "<p> My Function One </p>";
}
}

class MyClassTwo
{
private $myClassOne;

function __constructor() // WRONG WRONG WRONG - __construct() - and it works.
{
$this->myClassOne = new MyClassOne();
}

public function myFunctionTwo()
{
echo "<p> My Function Two </p>";
$this->myClassOne->myFunctionOne(); // This crashes the "application"
}

}


$myclassone = new MyClassOne();
$myclassone->myFunctionOne();
$myclasstwo = new MyClassTwo();
$myclasstwo->myFunctionTwo();


/*
Expectet result:
My Function One
My Function Two
My Function One

Real result:
My Function One
My Function Two
(application/runtime crash)
*/

?>


It will be highly appreciated if anyone can provide an explanation or show me the relevant documentation for this behavior.

Answer

You have a typo. Change __constructor to __construct and it will work correctly.

PHP constructors should be named __construct() as per the documentation.