PHP 5.3构造函数方法


PHP 5.3 constructor method

我是一名Java/c#程序员,正在尝试学习/完成PHP项目。谁能给我解释一下为什么"组合"在PHP 5.3中不能像人们期望的面向对象语言那样工作?

我试着研究这个问题,但由于术语混淆(使谷歌无用…)和糟糕的文档,我还没能找到任何有用的东西。

<?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)
*/
?>

如果有人能提供解释或向我展示有关此行为的相关文档,我将不胜感激。

你打错了。将__constructor更改为__construct,将正常工作。

PHP构造函数应该按照文档命名为__construct()