调用非对象上的成员函数 [英] Call to a member function on a non-object

查看:111
本文介绍了调用非对象上的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在重构代码以实现更多的OOP.我设置了一个用于保存页面属性的类.

So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.

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()函数

Later on I call the set_page_title() function like so

function page_properties($objPortal) {    
    $objPage->set_page_title($myrow['title']);
}

当我收到错误消息时:

在非对象上调用成员函数set_page_title()

Call to a member function set_page_title() on a non-object

那我想念什么?

推荐答案

这表示$objPage不是对象的实例.我们可以看到用于初始化变量的代码吗?

It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?

如您期望的是特定的对象类型,您还可以使用 PHP的类型提示功能 Docs 在违反逻辑时得到错误:

As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:

function page_properties(PageAtrributes $objPortal) {    
    ...
    $objPage->set_page_title($myrow['title']);
}

此函数仅将PageAtrributes用作第一个参数.

This function will only accept PageAtrributes for the first parameter.

这篇关于调用非对象上的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆