当我无法调用方法时,我遇到了问题。结构是这样的:
/www
/classes
/class.php
/pages
/page.php
/index.php
所以我想从页面.php文件中调用方法。自动加载器在索引.php文件中配置。正确的方法是什么?我在 index.php 中创建了对象,并在 page.php 中调用了方法,但它抛出了Fatal error: Call to a member function indexAboutMe() on a non-object in...
我认为,问题是索引.php文件没有将对象变量传递给页面.php。
我使用另一个类的方法包含页面(工作正常 - 包含 HTML,但无法调用方法,因为对象变量为空)。
法典:
索引.php
<?php
$page = $_GET['page'];
if (empty($page)){$page = 'sakums';}
function __autoload($class_name) {
include './classes/' . $class_name . '.php';
}
$active = new activePage();
$db = new database();
?>
//then there is bunch of plain html code
<?php
$pageSwitcher = new pageSwitcher();
$pageSwitcher->pageLoader($page);
?> //this is page switching method, which includes file from pages folder
包含页面的类:
<?php
/*
*class for page loading depending on active page.
*/
class pageSwitcher
{
public function pageLoader($page)
{
switch ($page)
{
case 'sakums':
include_once './pages/sakums.php';
break;
}
}
}?>
和 sakums.php它不能接收对象变量:
//html here
<?php $db->indexAboutMe(); ?>
//html
您可以在函数(包括页面)中实例化 $db
变量或使用global $db;