PHPメソッドのリロードに関する注意事項
2086 ワード
まず簡単な例を示します.
注意:子クラスのインスタンスで親を呼び出すメソッドは、親メソッドに子クラスの再ロード後のメソッドが含まれている場合、子クラスメソッドが優先的に呼び出されます.子クラスにこのメソッドがない場合、親クラスのメソッドが呼び出されます.
このような行為はpythonでも同様に成立します.
もう1つの特性は,CとC++では親クラスが子クラスを呼び出す方法は許されないがphpでは許されることに注目すべきである.呼び出しの例を次に示します.
参考サイト: php親呼び出しサブクラスメソッドおよびメンバー
';
}
public function alone()
{
echo 'alone
';
$this->one();
}
}
class ChildClass extends ParentClass
{
public function one()
{
echo 'child here
';
}
public function test()
{
$this->alone();
}
}
$child = new ChildClass();
$child->test();
//
alone
child here
注意:子クラスのインスタンスで親を呼び出すメソッドは、親メソッドに子クラスの再ロード後のメソッドが含まれている場合、子クラスメソッドが優先的に呼び出されます.子クラスにこのメソッドがない場合、親クラスのメソッドが呼び出されます.
';
}
public function alone()
{
echo 'alone
';
$this->one();
}
}
class ChildClass extends ParentClass
{
// public function one()
// {
// echo 'child here
';
// }
public function test()
{
$this->alone();
}
}
$child = new ChildClass();
$child->test();
//
alone
parent here
このような行為はpythonでも同様に成立します.
class ParentClass:
def one(self):
print "parent here"
def alone(self):
print "alone"
self.one()
class ChildClass(ParentClass):
def one(self):
print "child here"
def test(self):
self.alone()
c = ChildClass()
c.test()
//
alone
child here
もう1つの特性は,CとC++では親クラスが子クラスを呼び出す方法は許されないがphpでは許されることに注目すべきである.呼び出しの例を次に示します.
swim();
echo $this->fishNum;
}
}
class Fish extends Animal
{
public $fishNum=10;
public function swim()
{
echo 'Fish swim';
}
}
$fish=new Fish();
$fish->swim();
$fish->run();
//
Fish swimAniaml runFish swim10
参考サイト: