インターネットで見つけた簡単な OOP チュートリアルに従っています。ほぼ完了しましたが、トピックで言及したエラーが発生します。
出力は次のとおりです。
Stefan's full name: Stefan Mischook
Notice: Use of undefined constant name - assumed 'name' in C:\xampp\htdocs\oop\class_lib.php on line 21
---> JOHNNY FINGERS
こちらですindex.php:
<?php
require_once('class_lib.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OOP in PHP</title>
</head>
<body>
<?php
$stefan = new person("Stefan Mischook");
echo "Stefan's full name: " . $stefan->get_name();
echo "<br>";
$james = new employee("Johnny Fingers");
echo "---> " . $james->get_name();
?>
</body>
</html>
クラスを含むファイル、class_lib.php は次のとおりです。
<?php
// A variable inside a class is called a "property"
// Functions inside a class are called "methods"
class person
{
var $name; // If a property is declared with the "var" keywords it is considered public.
public $height;
protected $social_insurance;
private $pinn_number;
function __construct($persons_name)
{
$this->name = $persons_name;
}
protected function set_name($new_name)
{
if (name !="Jimmy Two Guns")
{
$this->name = strtoupper($new_name);
}
}
public function get_name()
{
return $this->name;
}
private function get_pinn_number()
{
return $this->$pinn_number;
}
}
class employee extends person
{
protected function set_name($new_name)
{
if ($new_name == "Stefan Lamp")
{
$this->name = $new_name;
}
else if ($new_name == "Johnny Fingers")
{
person::set_name($new_name);
}
}
function __construct($employee_name)
{
$this->set_name($employee_name);
}
}
// $this can be considered a special OO PHP keyword
// A class is NOT an object. The object gets created when you create an instance of the class.
// A handle is...
// To create an object out of a class you need to use the "new" keyword.
// When accessing methods and properties of a class you use the -> operator.
// A constructor is a built-in method that allows you to give your properties values when you create an object
// A private property can be accessed only by the same class.
// A protected property can be accessed by the same class and classes that are derived from that class.
// A public property has no access restrictions.
// Public, private and protected are called "acces modifiers" and it's all about control. It makes sense to control how people use classes.
// "extends" is the keyword that enables inheritance
// Child class methods can overwrite parent class methods simply by declaring a method with the same name again.
/* "::" allows you to specifically name the class where you want PHP to search for a method. If you want to access the method of the parent class instead of the overwritten one of the child class you can do it much simpler by calling it this way: parent::method() (you don't have to type the name of the class).*/
?>
コメントは気にしないでください。学習目的で使用します。どうもありがとうございました。評価を下げる前に質問を編集する必要がある場合はお知らせください。乾杯!