I started to touch PHP at work.
I naturally thought that if the field had a protected attribute, the grandchild class could refer to the parent class like Java, but even if I googled the mention of the grandchild class (unless my research was bad). There was a lot of talk about derived classes and child classes.
Meanwhile, in this post, I saw the description that protected is reflected only in the inheritance one step ahead in PHP, and actually try it.
PC Windows 8.1
Java Eclipse Kepler Service Release 2 jre8
PHP XAMPP Version 7.0.24 PHP Version 7.0.24
[2018/01/28 postscript] Place the following java file in the default package
//Parent class
abstract class Charactor {
protected String name = "Charactor";
}
//Child class
class HumanCharactor extends Charactor {
}
//Grandchild class
class Wizard extends HumanCharactor {
public Wizard (String name) {
this.name = name;
}
}
//Test code
class Main {
public static void main(String[] args) {
System.out.println("Test Start...");
Wizard wiz = new Wizard("Wizard");
System.out.println(wiz.name);
HumanCharactor human = new HumanCharactor();
System.out.println(human.name);
System.out.println("Test End...");
}
}
Test Start...
Wizard
Charactor
Test End...
[2018/01/28 operation check code replacement]
<?php
echo '<pre>';
//Parent class
abstract class Charactor {
protected $name = "Charactor";
}
//Child class
class HumanCharactor extends Charactor {
public function printName() {
var_dump($this->name);
}
}
//Grandchild class
class Wizard extends HumanCharactor {
public function __construct($name) {
$this->name = $name;
}
//If you call here, Fatal Error
//public function printName() {
// var_dump($this->name);
//}
}
//Test code
new Test();
class Test {
public function __construct() {
var_dump("Test Start...");
$wiz = new Wizard("Wizard");
$wiz->printName();
//var_dump($wiz->name);← This is a Fatal Error
$human = new HumanCharactor();
$human->printName();
//var_dump($human->name);← This is a Fatal Error
var_dump("Test End...");
echo '</pre>';
}
}
?>
string(13) "Test Start..."
string(6) "Wizard"
string(9) "Charactor"
string(11) "Test End..."
[2018/01/28 description correction] Like Java, PHP could use protected fields in its parent's parent class. However, unlike Java, PHP doesn't seem to be able to reference the parent field of the parent directly from an instance of the grandchild class.
Recommended Posts