Call to a member function on a non-object
所以我要重构我的代码来实现更多的OOP。我设置了一个类来保存页面属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class PageAtrributes { private $db_connection; private $page_title; public function __construct($db_connection) { $this->db_connection = $db_connection; $this->page_title = ''; } public function get_page_title() { return $this->page_title; } public function set_page_title($page_title) { $this->page_title = $page_title; } } |
稍后我会这样调用set_page_title()函数
1 2 3 | function page_properties($objPortal) { $objPage->set_page_title($myrow['title']); } |
当我收到错误消息时:
Call to a member function set_page_title() on a non-object
那我错过了什么?
这意味着
正如您所期望的特定对象类型一样,您也可以使用phps类型暗示featuredocs在违反逻辑时获取错误:
1 2 3 4 | function page_properties(PageAtrributes $objPortal) { ... $objPage->set_page_title($myrow['title']); } |
此函数只接受第一个参数的
有一种简单的方法可以产生这个错误:
1 2 | $joe = null; $joe->anything(); |
将呈现错误:
Fatal error: Call to a member function
anything() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
如果PHP只是说,
Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define
anything() in on line <##>.
通常,您已经构建了自己的类,这样在构造函数或
或者
也可能意味着,当初始化对象时,可能在代码的另一部分中重新使用了对象名。因此,将它的方面从一个对象更改为一个标准变量。
工业工程
1 2 3 4 5 6 7 8 9 10 11 12 | $game = new game; $game->doGameStuff($gameReturn); foreach($gameArray as $game) { $game['STUFF']; // No longer an object and is now a standard variable pointer for $game. } $game->doGameStuff($gameReturn); // Wont work because $game is declared as a standard variable. You need to be careful when using common variable names and were they are declared in your code. |
我推荐上面接受的答案。但是,如果手头紧,可以在page_properties函数中将对象声明为全局对象。
1 2 3 4 5 6 | $objPage = new PageAtrributes; function page_properties() { global $objPage; $objPage->set_page_title($myrow['title']); } |
1 2 3 | function page_properties($objPortal) { $objPage->set_page_title($myrow['title']); } |
看起来变量$objportal与$objpage的名称不同
您可以在函数中使用"use",如下面的示例
1 2 3 | function page_properties($objPortal) use($objPage){ $objPage->set_page_title($myrow['title']); } |
我意识到我没有将$objpage传递到page_properties()中。它现在工作得很好。