We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Http\Response - Trying to call method set on a non-object

Hey guys,

I wanted to continue on a project I started with phalcon 1 or 2 and got some trouble. My class AjaxResponse extends the phalcon response to add default behavior. When I instanciate the class I'm getting the following error.

Fatal Error:  Uncaught RuntimeException: Trying to call method set on a non-object in app\system\http\AjaxResponse.php:18
Stack trace:
#0 [internal function]: Phalcon\Http\Response->setHeader('Content-Type', 'application/jso...')
#1 app\system\http\AjaxResponse.php(18): Phalcon\Http\Response->setContentType('application/jso...', 'utf-8')
#2 app\system\exception\AjaxException.php(16): app\system\http\AjaxResponse->__construct()
#3 app\system\exception\SystemException.php(19): app\system\exception\SystemException->render()
#4 app\system\exception\AbstractException.php(21): app\system\exception\SystemException->run()
#5 app\system\exception\ErrorHandler.php(41): app\system\exception\AbstractException->__construct('Class 'snappy\\r...', 503, Object(Error))
#6 [internal function]: app\system\exception\ErrorHandler->handleException(Object(Error))
#7 {main}
  thrown in app\system\http\AjaxResponse.php on line 18

This is the related class

<?php
namespace app\system\http;
use Phalcon\Http\Response;

/**
 * This class is used to easily create a ajax response in form of a json string
 */
class AjaxResponse extends Response {

    /**
     * Initialize new ajax response
     *
     * @param mixed $data
     * @param bool $success
     * @param string $error
     */
    public function __construct($success = true, $data = null, $error = null) {
        $this->setContentType('application/json', 'utf-8');
    }
}

new AjaxResponse(true);

I checked with method_exists($this, 'setHeader') if the method exists and it does. So I can not see my failure here Can anyone help me? PS: I'm using latest PHP 7 and Phalcon 3.

Thanks in advance Best FragSalat



32.2k
Accepted
answer

Hey dude you have to overwrite and call the parent constructor because that create a instance of Header look

<?php
namespace app\system\http;
use Phalcon\Http\Response;

/**
 * This class is used to easily create a ajax response in form of a json string
 */
class AjaxResponse extends Response {

    /**
     * Initialize new ajax response
     *
     * @param mixed $data
     * @param bool $success
     * @param string $error
     */
    public function __construct($success = true, $data = null, $error = null) {
        parent::__construct($success, $data, $error);
        $this->setContentType('application/json', 'utf-8');
    }
}

new AjaxResponse(true);

Good luck

Yo thanks for the Hint. My call to the parent constructor was after the header setup which at least worked before :)