
もくじ
子クラスが親クラスのプロパティを上書きするケース
client.php
<?php require './ChildClass.php'; $instance_child = new ChildClass(); echo $instance_child->getName();
ChildClass.php
<?php
require './ParentClass.php';
class ChildClass extends ParentClass
{
public $name = "child";
}
ParentClass.php
<?php
class ParentClass
{
public $name = "parent";
public function getName()
{
return $this->name;
}
}
php client.php
結果
child
子クラスが親クラスのプロパティをメソッドで参照するケース
client.php
<?php require './ChildClass.php'; $instance_child = new ChildClass(); echo $instance_child->getName(); echo $instance_child->getParentName();
ChildClass.php
<?php
require './ParentClass.php';
class ChildClass extends ParentClass
{
public $name = "child\n";
public function getName()
{
return $this->name;
}
public function getParentName()
{
return parent::getName();
}
}
ParentClass.php
<?php
class ParentClass
{
public $parent_name = "parent\n";
public function getName()
{
return $this->parent_name;
}
}
php client.php
結果
child parent
子クラスから親クラスのプロパティを上書きする
client.php
<?php
require './ChildClass.php';
$instance_child = new ChildClass();
$instance_child->setName("child\n");
echo $instance_child->getName();
ChildClass.php
<?php
require './ParentClass.php';
class ChildClass extends ParentClass
{
public function setName(string $string)
{
$this->parent_name = $string;
}
}
ParentClass.php
<?php
class ParentClass
{
public $parent_name = "parent\n";
public function getName()
{
return $this->parent_name;
}
}
php client.php
結果
child
上記から、ParentClass::$parent_nameのアクセス修飾子をprivateにする
<?php
class ParentClass
{
private $_parent_name = "parent\n"; // ●publicからprivateに変更 ... 子クラスからの変更を許さない
public function getName()
{
return $this->_parent_name;
}
}
結果
parent
setName()での書き換えが出来ていないことが確認できます。
上記から、ParentClass::$parent_nameのアクセス修飾子をprotectedにする
<?php
class ParentClass
{
protected $parent_name = "parent\n"; // ●privateからprotectedに変更 ... 子クラスからの変更を許す
public function getName()
{
return $this->parent_name;
}
}
結果
child
書き換えができた
staticによる親・子別のプロパティ参照
client.php
<?php require './ChildClass.php'; $instance_child = new ChildClass(); echo $instance_child->getName();
ParentClass.php
<?php
class ParentClass
{
static protected $name = "parent\n";
}
ChildClass.php
<?php
require './ParentClass.php';
class ChildClass extends ParentClass
{
static public $name = "child\n";
public function getName()
{
echo self::$name;
echo parent::$name;
}
}
結果
child parent





