我正在学习OOP PHP。我想从另一个类调用一个方法到一个新的类。
仅作为示例:
<?php
class Aclass {
function aMethod($input)
{
echo 'Hello a world ';
}
}
?>
我想从类“ Aclass ”中将方法aMethod调用到新类中。
<?php
class Bclass {
//calling the method here?
}
?>
我尝试扩展,但仍然无法为我工作。
谢谢。
为此,我将使用依赖注入。这只是说“A
创建时发送类的对象”的一种奇特的方式B
。
换句话说,是这样的:
class typeA {
public function __construct () {};
public function test () {
return 'Test string';
}
}
class typeB {
protected $testObj;
public function __construct (typeA $testCase) {
$this->testObj = $testCase;
}
public function getTest () {
return $this->testObj->test ();
}
}
$a = new typeA ();
$b = new typeB ($a);
echo $b->getTest ();
构造函数是为了用来创建一个对象,是准备要被使用的,这就是为什么我刚刚存储在内部的依赖typeB
对象本身。然后,在getTest()
方法中,我调用test()
我所依赖的对象的方法,以便从中获取所需的数据。
以这种方式进行操作将使您能够编写灵活的OOP代码,可以根据需要轻松地对其进行扩展和扩展。通过在构造函数内部隐藏依赖项,可以在其中创建对象,从而创建隐藏且困难的依赖项。某种事情使得正确利用基于类的设计的可扩展性变得更加困难,即使不是完全不可能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句