【问题标题】:PHP Warning: get_class() expects parameter 1 to be object, null givenPHP 警告:get_class() 期望参数 1 是对象,给定 null
【发布时间】:2020-08-15 02:48:42
【问题描述】:
public function InitButton($Name, $Group, $T=0, $L=0, $W=1, $H=1, $BStyle=null, $Text='', $Expire = 0, $Repeat=true)
{
    $OldButton = ButtonManager::getButtonForKey($this->UCID, $Name);

    //Line 4 below: 
    if(get_class($OldButton) == 'Button') {

        $Button = $OldButton;
    } else {
        $Button = new Button($this->UCID, $Name, $Group);
    }
    $Button->T($T)->L($L)->W($W)->H($H);
    $Button->BStyle($BStyle);
    if(is_array($Text)) {
        $Button->Text($Text[0]);
        $this->bTexts[$Name] = $Text;
    } else {
        $Button->Text($Text);
        $this->bTexts[$Name][0] = $Text;
    }
    $Button->Send();

    $this->bState[$Name]['ID'] = 0;
    $this->bState[$Name]['timestamp'] = time() - 1;
    $this->bState[$Name]['override'] = false;
    if($Expire > 0) {
        $this->bState[$Name]['expire'] = time() + $Expire;
    } else {
        $this->bState[$Name]['expire'] = -1;
    }
    $this->bState[$Name]['repeatText'] = $Repeat;

}

PHP 警告:get_class() 期望参数 1 为对象,在第 4 行的 C:\Users\HP\Desktop\test\test.php 中给出 null

我该如何解决这个问题?

【问题讨论】:

  • $OldButton 为 null 而不是对象。使用 var_dump() 进行测试。

标签: php


【解决方案1】:

问题可能是$OldButton 可以是null,而您不能在null 值上调用get_class。显然,ButtonManager::getButtonForKey($this->UCID, $Name) 可以返回 null,这就是你的问题。您可以在第 4 行之前执行此操作来修复它:

if (!is_null($OldButton)) {
    if(get_class($OldButton) == 'Button') {
        ...
    }
}

【讨论】:

  • 快速说明,虽然此代码可以工作,但我建议您检查 null 并抛出错误,而不是检查 not null。这使您的代码更具可读性。
【解决方案2】:

这意味着ButtonManager::getButtonForKey($this->UCID, $Name); 返回null。如果这是预期行为,则可能将 if 语句更改为

if ($OldButton && get_class($OldButton) == 'Button')

这会检查按钮是否不为空,然后检查类是否为'Button'

如果不是预期的行为,则 ButtonManager 出现问题

【讨论】:

  • 谢谢。这解决了它
  • 如果确实如此,请您将其标记为已解决。这样未来的访问者可以立即找到正确答案
猜你喜欢
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多