这次我遇到了一个难题。我有:
[文件夹](文件)
结构目录
[class]
-(class.page.php)
-(class.main.php)
[核心]
-(core.test.php)
现在class.data.php
<?php
class DataTools {
public function clean($string) {
if (!empty($string)) {
$string = addslashes($string);
$string = mysql_real_escape_string($string);
$string = (string)$string;
$string = stripslashes($string);
$string = str_replace(" ", "", $string);
$string = str_replace("(", "", $string);
$string = str_replace("=", "", $string);
return $string;
} else {
echo "Error";
die();
}
}
现在class.page.php
<?php
class Page {
public function __construct {
include "class.data.php";
$data = New DataTools();
}
?>
现在core.test.php
<?php
require_once "../class/class.page.php";
$page = new Page;
$nome = $data->clean("exemple"); // line 13
?>
当我打开class.test.php时,它显示如下:致命错误:在第13行的/membri/khchapterzero/core.test.php中的非对象上调用成员函数clean()(这并不重要,因为我为主题缩减了页面,但原始页面中的行是我发布的,另一行是注释)
这似乎没问题,如果所有文件都在一个文件夹中,它运行良好,我尝试了一下,没有出现错误。检查你的结构和名字。我查看:
Test->
class.data.php
class.page.php
core.test.php
在仅包含文件名中。所以再次检查您的路径
$data是在Page对象中定义的,它在全局范围中不能作为变量使用。因为您没有将它存储为Page obejct的类成员,所以当Page的构造函数解析时,它也会丢失。
要解决此问题:
首先使$data成为Page类的类成员,这样在构造函数完成后就不会丢弃它
<?php
class Page {
public function __construct {
require_once "../include/class.data.php";
$this->data = New DataTools();
}
?>
然后,访问页面内的数据变量,而不是尝试直接调用$data:
$nome = $page->data->clean("exemple");