从包含的文件调用类方法,可以设置类变量,但不能调用方法/函数


call class method from included file, can set class variable but not call method/function

我有一个非常简单的类

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 $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'); ?>

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

相关文章: