0

there is my class Using $this when not in object context.

 <?php


class Adverts extends CActiveRecord
{
    public function getMainImage($id=0, $t=0){
         return $this->images($id, 'main-image', $t);
    }
   public static function mainPic($id, $t=0){
       $thumb = $t ? 'thumbs/':'';
       return self::urlDir($id).$this->getMainImage($id,$t);<---error line
   }

 .......

Why i can't call simple method in static method???

Doseke
  • 13
  • 4

3 Answers3

0

Actually static method mean that it method related to Class not to certain instance of this class, so that why you getting this error, you cant non-static methods in static.

nowiko
  • 2,507
  • 6
  • 38
  • 82
0

First at all you should know the difference between $this and self:

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

More information: When to use self over $this?

And you can't do that because you are trying to call a instance method from a static method, where you don't have the instance.

If you want to do that, you should change your method to static, and call it with self.

Or you could pass the instance as parameter and call it like instance->method.

More: PHP static method vs instance method

Community
  • 1
  • 1
Gonz
  • 1,198
  • 12
  • 26
0

$this is reference to Adverts object. This object is created when you are creating new class by calling new Adverts(). Now since you are calling static method like this Adverts::mainPic() you are not creating new class object. So that means inside mainPic() there is no such thing as class object that is located inside $this that's why you can't use it.

You can access other static methods or variables that does not use $this in these ways:

self::methodName() // access current class or parent class method
parent::methodName() // access method in parent class
Justinas
  • 41,402
  • 5
  • 66
  • 96