Discussion – Lesson 7 - Inheritance in PHP
BackComments
Member
5 messages from 5 displayed.
//= Settings::TRACKING_CODE_B ?> //= Settings::TRACKING_CODE ?>
Comments
im talking the parents and child ('ancestor and descendant')
decendant can use the method of their ancestor but the ancestor can't use the
methods of its decendants.. but why there is code that extends it for there
relationship please enlighten me
can you help me on this.. i got to call the protected method in via $carl = new Human and protected function tin() inside the class of human i once call it but i got this result
PHP Fatal error: Call to protected method Human::tin() from context '' in /home/jailphp/5a7e830970c31/index.php on line 77
here's ,my code
<?php
// Contents of the Human.php file
class Human
{
public $firstName;
public $lastName;
public $age;
private $tiredness = 0;
public function __construct($firstName, $lastName, $age)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->age = $age;
}
protected function sleep($time)
{
$this->tiredness -= $time * 10;
if ($this->tiredness < 0)
$this->tiredness = 0;
}
protected function tin(){
echo ($this->firstName . " " . $this->lastName);
}
public function run($distance)
{
if ($this->tiredness + $distance <= 20)
$this->tiredness += $distance;
else
echo("I'm too tired.");
}
public function greet()
{
echo('Hi, my name is ' . $this->firstName);
}
public function __toString()
{
return $this->firstName;
}
}
// Contents of the PhpProgrammer.php file
class PhpProgrammer extends Human
{
public function program()
{
echo("I'm programming in {$this->ide}...");
}
protected function zion(){
return ($this->firstName . " " . $this->lastName);
}
}
// Contents of the index.php file
require_once('classes/Human.php');
require_once('classes/PhpProgrammer.php');
$carl = new Human('Carl', 'Smith', 30);
$john = new PhpProgrammer('John', 'New', 24, 'Eclipse');
//$john->greet(); it work
//$carl->program(); it doesn't work
//$john->tin(); not working called in PhpProgrammer instanceprotected!!
//$carl->tin(); not working called in Human Class protected
//$carl->tin(); not working called in Human Class protected
?>
Hi Justin,
you can call protected methods only from within the class. Only
public
methods can be called on the variable carrying the instance.
You can call $this->tin()
anywhere in the code of the
PhpProgrammer
class, but not outside of it.
Thans david i fiugre it our.. like
class human {
protected function tin(){
echo ($this->firstName . " " . $this->lastName);
}
class PhpProgrammer extends human{
public function zion() {
echo $this->tin();
}
}
include(classess/Human.php);
$carl = new human();
$joseph = new PhpProgrammer();
$joseph->zion(); // in this i can call protected methods in parent human
5 messages from 5 displayed.