OO PHP Functions


OO PHP Functions

我对 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() - works

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

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

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

.php上面的do_shortcode可以毫无问题地访问函数并完成工作,但是我需要测试中的以下函数.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

编写 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
}

当文件包含在函数中时,它们只能从该函数的作用域访问:

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

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