PHP 如何从另一个类和另一个文件调用函数


PHP How to call a function from another class and another file?

index.php

include('./class1.php');
include('./class2.php');
$Func = new function();
$Func->testfuncton1();

类1.php

class controller{
  public function test(){
    echo 'this is test';
  }
}

类2.php

class function{
  public function testfuncton1(){
    controller::test();
  }
}

但是我们不会从函数test()获取内容。

请告诉我哪里有错误?

您的问题:

  • 您不能有一个名为 functionclassfunction是一个keyword.
  • 您初始化$Func,但使用$Function进行调用

如果删除这两个问题,代码将正常工作:

class ClassController{
  public function test(){
    echo 'this is test';
  }
}
class ClassFunction{
  public function testfuncton1(){
    ClassController::test();
  }
}
$Func = new ClassFunction();
$Func->testfuncton1();

这应该打印this is a test