Php 如何将一个类中的函数转换为另一个类中的另一个函数
我试图使用一个类中的函数,并在另一个类中的另一个函数中使用它。 classTest.phpPhp 如何将一个类中的函数转换为另一个类中的另一个函数,php,wordpress,function,class,Php,Wordpress,Function,Class,我试图使用一个类中的函数,并在另一个类中的另一个函数中使用它。 classTest.php class Test extends WC_Payment_Gateway{ public function testing(){ $anotherClass = new anotherClass; $anotherClass->testFunction(); } } anotherClass.php class anotherClass{ pu
class Test extends WC_Payment_Gateway{
public function testing(){
$anotherClass = new anotherClass;
$anotherClass->testFunction();
}
}
anotherClass.php
class anotherClass{
public function testFunction(){
echo "This is the test function";
}
}
我希望我在你的
classTest.php
首先包含anotherClass.php
,然后使用$anotherClass=new anotherClass()创建另一个类的对象
并调用另一个类的函数$anotherClass->testFunction()代码>
或
在本例中,首先创建a
类的新实例。在此之后,我创建了B
类的一个新实例,并将a
的实例传递给构造函数。现在B
可以使用$this->A
访问A
类的所有公共成员
还要注意的是,我没有在B
类中实例化A
类,因为这意味着我会将这两个类临时耦合起来。这使得很难:
单元测试你的B
类
将A
类换成另一个类
您可以从任何其他类调用函数,只需将所需的类包含到php文件中即可,因此在您的示例中,如果要调用测试函数:
<?php
include_once('anotherClass.php');
class Test extends WC_Payment_Gateway{
public function testing(){
$anotherClass = new anotherClass;
$anotherClass->testFunction();
}
}
我添加了include('Test/src/anotherClass.php')代码>但我收到一个错误致命错误:未找到类“anotherClass”
class A
{
private $name;
public function __construct()
{
$this->name = 'Some Name';
}
public function getName()
{
return $this->name;
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
function getNameOfA()
{
return $this->a->getName();
}
}
$a = new A();
$b = new B($a);
$b->getNameOfA();
<?php
include_once('anotherClass.php');
class Test extends WC_Payment_Gateway{
public function testing(){
$anotherClass = new anotherClass;
$anotherClass->testFunction();
}
}