构造方法返回完整的类Object,即使我调用其他函数

时间:2015-03-06 05:35:22

标签: php oop

首先是我的班级代码,

class Gateway extends Gateways
{
public function __construct($id = false)
{
    parent::__construct();

    if($id) return $this->getById($id);
}

public function getById($id)
{
    $this->gateway_select->columns($this->cols)->where(array($this->columns['ID'] => $id, $this->columns['IS_ACTIVE'] => 1));
    return $this->_fetch();
}

protected function _fetch()
{
    $this->gateway_select->limit(1);
    //echo $this->sql->getSqlStringForSqlObject($this->gateway_select);
    $result = $this->sql->prepareStatementForSqlObject($this->gateway_select)->execute()->current();
    return $result;
}

现在当我在其他文件中调用此代码时

$gatewayRow = new Gateway($gatewayId);

print_r($gatewayRow);
exit;

输出结果是Gateway类Object而不是从getById($ id)方法获取的数据库行,但据我所知,返回需要是数据库行。

当我单独调用getById()方法时,如$gateway->setById($id);它可以工作,所以它的东西与__construct()

parent :: __构造代码

public function __construct()
{
    $this->db = TechMediaStudios::dbInstance();
    $this->sql = TechMediaStudios::sqlInstance();
    $this->gateway_select = $this->sql->select()->from($this->table);
    $this->_getColumns();
}

1 个答案:

答案 0 :(得分:1)

你不能return来自构造函数,期间的任何东西。构造函数只能设置对象或抛出异常,它不能返回任何内容。无论您在何处编写new Foo,结果都将是Foo的对象实例,而不是其他内容。这不能被覆盖。