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

1 php class

的index.php

include('./class1.php');
include('./class2.php');

$Func = new function();
$Func->testfuncton1();
Run Code Online (Sandbox Code Playgroud)

class1.php

class controller{

  public function test(){
    echo 'this is test';
  }
}
Run Code Online (Sandbox Code Playgroud)

class2.php

class function{

  public function testfuncton1(){
    controller::test();
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我们没有从功能中获得内容test().

请告诉我哪里有错误?

rai*_*ace 5

你的问题:

  • 你不能有一个class名字function.function是一个keyword.
  • 您初始化$Func,但使用$Function

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

class ClassController{

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

class ClassFunction{

  public function testfuncton1(){
    ClassController::test();
  }
}

$Func = new ClassFunction();
$Func->testfuncton1();
Run Code Online (Sandbox Code Playgroud)

这应该打印 this is a test

  • @vascowhite:您是否尝试过,或只阅读文档?:)给我看一个PHP 5的版本,它将无法工作..不要一直信任文档:) (2认同)