PHP object _construct function

2019-02-28 16:19发布

I have the following code

<!doctype html>
<head>
<meta charset = "utf-8">

<title>Objects</title>
</head>

<body>

    <?php

    class firstClass
    {
        function _construct($param)
        {
            echo "Constructor called with parameter $param";
        }
    }

    $a = new firstClass('one');
    ?>

</body>
</html>

When i run this code nothing is outputted in the browser, the tutorial i am following says this code should output "Constructer called with parameter apples", what is the problem?

标签: php oop object
2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-28 16:51

The constructor should be __construct() with two underscores.

http://php.net/manual/en/language.oop5.decon.php

And it will output "Constructor called with parameter one" in your code.

查看更多
看我几分像从前
3楼-- · 2019-02-28 17:03

You have missed a '_' in the constructor definition.

function _construct($param) => defines a function called _construct with one parameter
function __construct($param) => defines custom constructor with one parameter

The code should be like this:

<?php

    class firstClass
    {
         function __construct($param)
        {
            echo "Constructor called with parameter $param";
        }
    }

    $a = new firstClass('one');
?>
查看更多
登录 后发表回答