user2713275
user2713275

Reputation:

Accessing private variable in PHP's code

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?

Upvotes: 0

Views: 147

Answers (1)

duellsy
duellsy

Reputation: 8577

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

Upvotes: 5

Related Questions