[英]OO PHP Functions
我對PHP OOP還是很陌生,我遇到的問題是我無法將我的頭放在腳本的以下布局周圍:
沒有人有任何指針或方向。 我嘗試使用Google搜索,但是無法找到與我嘗試執行的操作遙不可及的任何操作。
它開始於:-作品
$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
當文件包含在函數中時,它們只能從該函數的作用域進行訪問:
http://php.net/manual/zh/function.include.php#example-136
您需要將所創建的對象的引用提供給包含文件的函數,或者將其拉入該函數的作用域以對其進行訪問。
編寫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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.