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

Handling $this in classes

Hi all,

Phalcon handles $this in classes in a weird way. Could you please explain the behavior below?

Class Foobar {
    public function one() {
        $this->two();
        // The above like does not work as "$this" refers to something else in Phalcon (?)

        Foobar::two();
        // This works flawlessly. I'm wondering what's the performance overhead (if any)
    }

    public function two() {
        echo "I'm function two()";
    }
}

Can't get such thing as you.

This is my testing library:

<?php
namespace Example\Library;

class TestClass {
  public function one() {
    echo 'Inside of TestClass.one()' . PHP_EOL;
    $this->two();
  }

  public function two() {
    echo 'Inside of TestClass.two()' . PHP_EOL;
  }
}

This is my testing controller:

<?php
namespace Example\Controllers;

class IndexController extends \Phalcon\Mvc\Controller {
  public function indexAction() {
    echo 'Inside of #Index controller' . PHP_EOL;

    echo 'Testing a normal "new" invocation: ' . PHP_EOL;
    $library = new \Example\Library\TestClass();
    $library->one();

    echo 'Testing as a service invocation:' . PHP_EOL;
    $this->library->one();
  }
}

And when i run it i got:

Inside of #Index controller
Testing a normal "new" invocation: 
Inside of TestClass.one()
Inside of TestClass.two()
Testing as a service invocation:
Inside of TestClass.one()
Inside of TestClass.two()

Ok, thanks. I guess I would need to dig deeper in my code.

How $this works is central to PHP - I don't think Phalcon changes it, or even could if it wanted to. Do a print_r($this) to see what it actually is.