Hi
I'm having issue of understand how to echo a variable when the class
is extended
. I have 2 files.
This is my index.php file:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OOP Example</title>
<?php include("class.php"); ?>
</head>
<body>
<?php
$mitch = new person("Mitch Last");
echo "Mitch's full name: " . $mitch->get_name();"</br>";
$last = new coworker("Last Mitch");
echo "</br>Last's full name: " . $last->get_name();"</br>";
$slim = new coworker("Slim Jim");
echo "</br>Slim's full name: " . $slim->get_name();"</br>";
?>
</body>
</html>
This is my class.php file:
<?php
class person {
// To defined adding class properties are optional
var $name;
function __construct($new_person) {
$this->name = $new_person;
}
public function get_name() {
return $this->name;
}
//protected methods and properties restrict access to those elements.
protected function set_name($new_name) {
if (name != "Slim Jim") {
$this->name = strtoupper($new_name);
}
}
}
// 'extends' is the keyword that enables inheritance
class coworker extends person {
protected function set_name($new_name) {
if ($new_name == "Mitch thinks") {
$this->name = $new_name;
}
else if($new_name == "Last thoughts") {
parent::set_name($new_name);
}
}
function __construct($coworker_name) {
$this->set_name($coworker_name);
}
}
?>
The issue is on my index.php file.
<?php
$mitch = new person("Mitch Last");
echo "Mitch's full name: " . $mitch->get_name();"</br>";
$last = new coworker("Last Mitch");
echo "</br>Last's full name: " . $last->get_name();"</br>";
$slim = new coworker("Slim Jim");
echo "</br>Slim's full name: " . $slim->get_name();"</br>";
?>
Right now when I echo it out, it looks like this:
Mitch's full name: Mitch Last
Last's full name:
Slim's full name:
When I change new coworker()
to new person()
then it echo out like this:
Mitch's full name: Mitch Last
Last's full name: Last Mitch
Slim's full name: Slim Jim
I'm confused on why new coworker()
is not echoing it. I'm still new to OOP.
Any Suggestions and explanation will help. I appreciate it. Thanks!