【问题标题】:call class method from included file, can set class variable but not call method/function从包含的文件中调用类方法,可以设置类变量但不能调用方法/函数
【发布时间】:2011-07-18 13:10:35
【问题描述】:

我有一个非常简单的课程

if(!isset($_GET['page'])) {
    $_GET['page'] = "home";

}

class be_site {

    var $thelink;

    public function get_static_content($page) {

        $this->check_path($page);

    } // end function

    private function check_path($pathfile) {

        if(file_exists($pathfile)) {
          $b = 1;
          include_once($pathfile);
        } else {
          $b = 2;
          include_once('error_page.php');
        }

    }// End Function

    public function selectedurl($subpage, $linkname){
        if($subpage == $this->thelink) {
            echo "<strong>" . $linkname . "</strong>";              
        } else {
            echo $linkname;
        }// End if

    } // End function


 } /// End site class

现在我在 index.php 中创建一个新对象

include('connections/functions.php'); $site_object = new be_site;

内容是我有的

//get file
if(isset($_GET['subpage'])){
  $site_object->get_static_content('content/' . $_GET['subpage'] . '.php');
       }else {
  $berkeley_object->get_static_content('content/' . $_GET['page'] . '.php');
}

好的,一切正常。但是,如果调用了包含的页面,我会尝试使用我的其他方法来包装链接,如果根据 $_GET['page'] 值选择它,则将其设为粗体。

例如

<ul>
    <li><a href="index.php?page=team&amp;subpage=about" target="_self" title="opens in same window" >
    <?php $site_object->thelink = "about_us";
          $site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
    </a>
    </li>...

对于每个链接等等。 现在可以在对象中设置变量但不能调用方法。我得到了错误

   Fatal error: Call to undefined method stdClass::selectedurl()

只是想知道为什么我可以从包含的文件中设置类中的 $thelink 变量,但不能调用公共函数?

谢谢

【问题讨论】:

    标签: php class include call


    【解决方案1】:

    更改此代码:

    <?php $site_object->thelink = "about_us";
          $site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
    

    到这里:

    <?php 
          global $site_object;
          $site_object->thelink = "about_us";
          $site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
    

    这不起作用的原因是由于在函数中使用包含的性质。如果在函数 (be_site::check_path) 中使用 include,则变量范围特定于该函数。请参阅http://php.net/manual/en/function.include.php 示例 #2。

    【讨论】:

    • 啊,是的。哦!我忘记了我必须在全局范围内声明它,因为即使包含的文件现在是它的一部分,它仍然在范围之外。
    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多