PHP object _construct function

2019-02-28 16:34发布

问题:

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?

回答1:

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.



回答2:

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');
?>


标签: php oop object