【问题标题】:How to get a function from one class into another function in another class如何从一个类中获取一个函数到另一个类中的另一个函数
【发布时间】:2016-08-10 10:51:11
【问题描述】:

我正在尝试使用一个类中的函数并在另一个类的另一个函数中使用它。 类测试.php

class Test extends WC_Payment_Gateway{
    public function testing(){
       $anotherClass = new anotherClass;
       $anotherClass->testFunction();
    }
}

另一个类.php

class anotherClass{
    public function testFunction(){
        echo "This is the test function";
    }
}

我希望我说得通

【问题讨论】:

    标签: php wordpress function class


    【解决方案1】:

    您可以从任何其他类调用函数,只需将所需的类包含到您的 php 文件中,因此在您的示例中,如果您想调用测试函数:

    <?php
    include_once('anotherClass.php');
    
    class Test extends WC_Payment_Gateway{
        public function testing(){
           $anotherClass = new anotherClass;
           $anotherClass->testFunction();
        }
    }
    

    【讨论】:

      【解决方案2】:

      在你的classTest.php

      首先包含anotherClass.php,然后使用$anotherClass = new anotherClass();创建另一个类的对象并调用另一个类的函数$anotherClass-&gt;testFunction();

      include ("anotherClass.php");
      class Test extends WC_Payment_Gateway{
          public function testing(){
             $anotherClass = new anotherClass();
             $anotherClass->testFunction();
          }
      }
      

      或者

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

      在这个例子中首先创建一个A 类的新实例。之后,我创建了B 类的新实例,我将A 的实例传递给构造函数。现在B 可以使用$this-&gt;a 访问A 类的所有公共成员。

      还要注意,我没有在 B 类中实例化 A 类,因为这意味着我将这两个类紧密结合。这使得很难:

      1. B 类进行单元测试
      2. A 类换成另一个类

      【讨论】:

      • 我添加了include('Test/src/anotherClass.php');,但出现错误Fatal error: Class 'anotherClass' not found
      猜你喜欢
      • 1970-01-01
      • 2016-01-09
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多