【问题标题】:Call method from subfolder从子文件夹调用方法
【发布时间】:2013-09-22 04:18:08
【问题描述】:

当我无法调用方法时,我遇到了问题。 structere 类似于:

/www
  /classes
    /class.php
  /pages
    /page.php
  /index.php

所以我想从 page.php 文件中调用方法。 自动加载器在 index.php 文件中配置。 这样做的正确方法是什么?我在 index.php 中创建了对象,并在 page.php 中调用了方法,但它抛出了Fatal error: Call to a member function indexAboutMe() on a non-object in...

我认为,问题是 index.php 文件没有将对象变量传递给 page.php。

我使用另一个类的方法来包含页面(工作正常 - 包含 html,但不能调用方法,因为对象变量为空。),这会导致这个错误吗?

代码:

index.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

【问题讨论】:

  • 在尝试调用方法之前是否实例化了一个对象?
  • 是的,在 index.php 的开头-
  • 您能否向我们展示您迄今为止尝试过的代码?

标签: php class oop methods


【解决方案1】:

您可以在包含页面的函数中实例化$db变量或使用global $db;

【讨论】:

  • php.net/manual/en/language.variables.scope.php 了解更多信息,很高兴回答 stackOverflow 中的第一个问题
  • 是的,我读到了变量范围,这就是为什么我很困惑,$db 是在 index.php 中启动的,所以它是全局的,但它没有将它传递给 page.php。
猜你喜欢
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 2011-07-08
  • 1970-01-01
相关资源
最近更新 更多