0

Why doesn't the following output the data I'm expecting?

class student
{
    private $name;
    private $id;

    public function _construct($name,$id)
    {
        $this->name = $name;
        $this->id = $id; 
    }

    public function getName()
    {
        return $this->name;
    }

    public function getID ()
    {
        return $this->id;
    }
}
$mhs = new student("budi","152012102");

echo "name = ".$mhs->getName();

I don't know what's happening, help?

6
  • name=$nama; whats your nama boy? Commented Mar 3, 2014 at 10:45
  • oh that just a TYPO ,AFTER I FIX IT, IT STILL DOESN'T OUTPUT THE 'name' Commented Mar 3, 2014 at 10:46
  • helo, u can test the the code here writecodeonline.com/php , or in your IDE , it just doesnt output the 'name' Commented Mar 3, 2014 at 10:48
  • 1
    Also _construct should be __construct Commented Mar 3, 2014 at 10:49
  • @febri23: DON'T SHOUT, WE CAN READ LOWER-CASE LETTERS, TOO. And while all upper-case comments aren't considered good form, a class name should start with an UpperCase, and the rest of the name is CamelCased... just so you know: php-fig.org Commented Mar 3, 2014 at 10:51

1 Answer 1

5

Two problems:

1) Calling the constructor

When you call the constructor, you need to prefix it with TWO underscores.

So in full, you constructor should be:

public function __construct($name, $id)
{
    $this->name = $name;
    $this->id = $id;
}

2) Typo

There also seems to be a simple typo in your constructor:

You're assigning $nama instead of $name

$this->name = $nama;

This should be

$this->name = $name;

[EDIT] This typo seems to be fixed in the main question now

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

8 Comments

oh that just a TYPO ,AFTER I FIX IT, IT STILL DOESN'T OUTPUT THE 'name'
Why is this wrong answer upvoted? You cant access private variables like that.
so how should i access the private variable ??
@YUNOWORK it's in the constructor, the answer is correct...the code should output the desired string
noticed another issue with the constructor, modified my answer (see section 1)
|

Your Answer

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