【发布时间】:2020-05-23 12:36:02
【问题描述】:
当我在做一个学校项目时,我遇到了一个问题。
我创建了一个路由器类,它可以在其中获取正确的文件,但出现以下错误:
致命错误:方法 mvc\App::__toString() 不得抛出异常,已捕获错误:调用 /opt/lampp/htdocs/School/testPHP/mvc/public/ 中字符串上的成员函数 getHTML()第 0 行的 index.php
回显返回正确的文件路径,所以这不是我遇到的问题。
我认为问题在于我尝试将函数执行到字符串中。
有人知道如何解决我的问题吗?
应用类:
<?php
namespace mvc;
class App{
private $router;
public function __construct(){
$this->router = new \mvc\Router();
}
public function __toString(){
try {
echo $this->router->getView(); //this returns the correct file path
return $this->router->getView()->getHTML();
} catch (Exception $e) {
return $e.getMessage;
}
}
}
?>
Router.php:
<?php
namespace mvc;
class Router{
private $route;
private $view;
private $controller;
private $model;
public function __construct(){
require_once(LOCAL_ROOT. "php/Routes.php");
if (isset($_GET['route'])){
$this->route = explode("/" , $_GET['route']);
}
$route = isset($routes[$this->getRoute()])? $this->getRoute() : DEFAULT_ROUTE;
$this->controller = "\\controllers\\". $routes[$route]['controller'];
$this->view = "\\views\\". $routes[$route]['view'];
// $model = "\\models\\". $routes[$route]['model'];
}
private function getRoute(){
return count($this->route) > 0 ? $this->route[0] : DEFAULT_ROUTE;
}
public function getView(){
return $this->view;
}
}
?>
Routes.php
<?php
define("DEFAULT_ROUTE", "home");
$routes = array(
"home" => array(
"view" => "HomeView",
"controller" => "HomeController",
),
"form" => array(
"view" => "FormView",
"controller" => "FormController",
),
"test" => array(
"view" => "TestView",
"controller" => "TestController",
),
)
?>
TestView.php
<?php
namespace views;
class TestView extends \mvc\View{
public function getHTML(){
// return 'dit is testView';
$klik = $this->controller->getGetData("klik");
$output = "";
$output .= "<h1>".$klik++ ."</h1>";
$output .= "<a href=\"test?klik=$klik\">klik</a>";
$output .= "<br>";
return $output;
}
}
?>
【问题讨论】:
-
你不能从
__toString()方法抛出异常。你可以在 PHP 版本 PHP 7.4 中做到这一点。 -
我们需要查看
Router类的代码,特别是getView()和getHTML()方法。 -
@MarkOverton 我已经添加了一些代码希望它是你需要的
-
简短回答:您不能像在 JavaScript 中那样在 PHP 字符串上调用方法,因为它们是原语。您可以将字符串作为参数传递给函数。
-
return $e.getMessage;在你的 App 类中没有做你想做的事;正确的语法是return $e->getMessage();。虽然这不能解决根本原因,但解决这个问题听起来是不错的第一步。
标签: php