Jump to content

PHP constructor in inherited classes

- - - - -

  • Please log in to reply
2 replies to this topic

#1
proteus

proteus

    Newbie

  • Members
  • Pip
  • 2 posts
I'm having problems defining a constructor with different arguments for my inherited class.

class Person {

	protected $m_name;

	protected $m_age;

	

	function __construct($name, $age) {

		$this->m_name = $name;

		$this->m_age  = $age;

	}

	

	public function SayHello() {

		echo $this->m_name . ", age " . $this->m_age . " says hello!";

	}

}


class Student extends Person {

	protected $m_grade;

	

	function __contruct($name, $age, $grade) {

		parent::__construct($name, $age);

		$this->m_grade = $grade;

	}

	

	public function SayHello() {

		echo $this->m_name . ", age " . $this->m_age . " says hello! (Grade: " . $this->m_grade . ").";

	}

}


$Bob = new Person('Bob', 29, 5);

$Bob->SayHello();

echo '<br />';

$Bill = new Student('Bill', 21, 5);

$Bill->SayHello();


Output:
Bob, age 29 says hello!

Bill, age 21 says hello! (Grade: ).
Variable $m_grade never gets a value. I saw this in a tutorial here but I can't see what I'm doing wrong. How can I accomplish this?

#2
itatcho

itatcho

    Newbie

  • Members
  • Pip
  • 3 posts
Hi,

you have forgotten the "s" in the name constructor in the Student class !

With the "s", it's work !

#3
proteus

proteus

    Newbie

  • Members
  • Pip
  • 2 posts
Thanks, that was embarrassing. I've been so spoiled with modern IDEs that I don't notice my own typos anymore when using a good old text editor :o




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users