1

我对 PHP OOP 还很陌生,我遇到的问题是我无法理解我的脚本的以下布局:

  • 设置主类,它设置页面并扩展 mysql 类并通过 __construct 创建数据库连接
  • 在主类中,我运行一个公共函数,该函数包含()一个文件并访问该包含文件中的一个函数
  • 在包含文件中的函数中,我似乎无法通过实际的全局变量或使用 $this->blah 访问主类

有没有人有任何指示或方向。我试着用谷歌搜索它,但找不到任何与我试图做的事情相近的东西。

它开始于: - 作品

$gw = new GWCMS();

然后在 GWCMS() 的 _construct 内部,GWCMS 扩展了 mySQL - 工作

parent::__construct(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->build();

然后它调用 build() - 工作

public function build(){
   ...
   $page['content'] = $this->plugins($page['content']);
   ...
   $output = $this->output($theme,$page);
   echo eval('?>' . $output);
}

调用 plugins() - 我们开始遇到问题

public function plugins($content){
   $x = 0;
   if ($handle = opendir(STOCKPLUGINPATH)) {
      while (false !== ($entry = readdir($handle))) {
         if(is_dir(STOCKPLUGINPATH . $entry . '/') && $entry != '.' && $entry != '..'){ 
            if(file_exists(STOCKPLUGINPATH . $entry . '/inc.php')){
               include(STOCKPLUGINPATH . $entry . '/inc.php');
               $content = do_shortcode($content);
            }
         }
      }
      closedir($handle);
   }
   return $content;
}

前面的代码包括 inc.php ,其中列出了要包含的文件:

include(STOCKPLUGINPATH . 'Test/test.php'); 

test.php 包含函数列表。上面的 do_shortcode 可以毫无问题地访问函数并完成工作,但是我需要 test.php 中的以下函数来访问 $gw->fetchAssoc(); 哪个 fetchAssoc 在 gwcms 的父级中

function justtesting2($attr){
   $config = $gw->fetchAssoc("Select * from gw_config");
   foreach($config as $c){
      echo $c['value'];
   }
}

当我运行脚本时,我得到

Fatal error: Call to a member function fetchAssoc() on a non-object in /home/globalwe/public_html/inhouse/GWCMS/gw-includes/plugins/Test/test.php on line 9
4

2 回答 2

0

当文件包含在函数中时,它们只能从该函数的范围内访问:

http://php.net/manual/en/function.include.php#example-136

您需要将对您创建的对象的引用提供给包含该文件的函数,或者将其拉入该函数的范围以访问它。

于 2012-06-27T16:18:35.453 回答
0

编写 OOP 代码意味着进行重组,以避免将文件和函数的混乱放入任何文件中,而天知道什么不是。

尝试依靠编写一个模拟您想要实现的行为的类。该类应包含为您携带数据的属性值和帮助该类表现得像您正在对其建模的事物的方法。

要回答您的问题:

class MyClass {
    public $my_property = 4;
    public function MyMethod() {
        include('file.php');
    }
    public function MyOtherMethod() {
        $this; // is accessible because MyOtherMethod
               // is a method of class MyClass
    }
}

// contents of file.php

$variable = 3;

function MyFunction($parameter) {
    global $variable; // is accessible
    $parameter; // is accessible
    $this // is not accessible because it was
          // not passed to MyFunction as a parameter
          // nor was it declared as a global variable

    // MyFunction is not a method of class MyClass,
    // there is no reason why $this would be accessible to MyFunction
    // they are not "related" in any OOP way
    // this is called variable scoping and/or object scoping
}
于 2012-06-27T16:20:00.223 回答