开发者

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

I have a very simple class

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

Now I create a new object in the index.php

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

In the content are I have

//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');
}

Ok so all working fine. But if an included page is called I use try to use my other method to wrap a link and make it bold if it is selected depending on the $_GET['page'] value.

for instance

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

And so on for each link. Now can set the variable in the object but not call the method. I get the error

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

Just wondered why I am able to set the $thelink variable in the class from an included file but not call a public function?

Thanks


Change this code:

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

To this:

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

The reason this isn't working is due to the nature of using include within a function. If you use include inside a function (be_site::check_path), the variable scope is specific to that function. See http://php.net/manual/en/function.include.php example #2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜