Fatal error: Call to a member function setAttribute() on a non-object in Magento

本文解决升级至Magento 1.4.20版本后出现的Fatal error问题,通过修改Abstract.php及Form.php文件中特定行的代码实现问题的修复。

升级到1.4.20版本,出现 Fatal error: Call to a member function setAttribute() on a non-object in 的错误,有些头痛,后来网上找到解决办法:

在app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php 第374行 将

$this->_source = Mage::getModel($this->getSourceModel())

->setAttribute($this);

改为:

if(is_object(Mage::getModel($this->getSourceModel()))){

$this->_source = Mage::getModel($this->getSourceModel())

->setAttribute($this);

}

然后再找到/app/code/core/Mage/Adminhtml/Block/Widget/Form.php 第201、202行将

$element->setValues($attribute->getSource()->getAllOptions(true, true));

改为:

if(is_object($attribute->getSource())){

$element->setValues($attribute->getSource()->getAllOptions(true, true));

}

到这里基本上问题会解决,如果还是不行请看原文,

原文地址是http://blog.logicalquest.com/php/magento/fatal-error-call-to-a-member-function-setattribute-on-a-non-object-in/

 

在PHP代码中出现 `Call to a member function prepare() on null` 错误,通常是因为尝试在一个 `null` 值上调用 `prepare()` 方法。在提供的 `DatabaseConfig` 类中,这意味着 `$pdo` 属性可能为 `null`。以下是可能的原因及解决办法: ### 1. 数据库连接失败 在 `__construct()` 方法中,如果数据库连接失败,`$pdo` 属性将不会被正确初始化,从而导致后续调用 `prepare()` 方法时出错。可以在 `catch` 块中添加日志记录,方便排查问题。 ```php class DatabaseConfig { private static $instance = null; private $pdo; private function __construct() { $host = 'localhost'; $dbname = 'recharge_site'; $username = 'root'; $password = ''; try { $this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->pdo->exec("SET NAMES 'utf8'"); $this->pdo->exec("SET time_zone = '+08:00'"); } catch (PDOException $e) { // 记录错误日志 error_log("数据库连接失败: " . $e->getMessage()); die("数据库连接失败: " . $e->getMessage()); } } public static function getInstance() { if (self::$instance == null) { self::$instance = new DatabaseConfig(); } return self::$instance->pdo; } // 防止克隆对象 private function __clone() { } } ``` ### 2. 调用方式错误 确保在调用 `getInstance()` 方法时没有出现错误。以下是一个正确的调用示例: ```php $pdo = DatabaseConfig::getInstance(); try { $stmt = $pdo->prepare("SELECT * FROM your_table"); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($result); } catch (PDOException $e) { echo "查询出错: " . $e->getMessage(); } ``` ### 3. 单例模式问题 确保单例模式的实现没有问题,避免在代码的其他地方意外重置 `$instance` 或 `$pdo`。 通过以上步骤,应该可以解决 `Call to a member function prepare() on null` 错误。如果问题仍然存在,需要进一步检查数据库服务器的配置和权限。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值