Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将一个类中的函数转换为另一个类中的另一个函数_Php_Wordpress_Function_Class - Fatal编程技术网

Php 如何将一个类中的函数转换为另一个类中的另一个函数

Php 如何将一个类中的函数转换为另一个类中的另一个函数,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

我试图使用一个类中的函数,并在另一个类中的另一个函数中使用它。 classTest.php

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();
        }
    }