1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

No problem, we were all newbies at one point. Glad I could help. Can you mark my answer as the correct one?
Actually shouldn't he echo $a aswell? Looks like he's only creating the object
@icecub No, he's echoing in the constructor.
@gnarly it says i have to wait five more minutes but i will when the time is up
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.