0

I have a code here,

class someClass { public $someMember; public function __construct() { $this->someMember = 1; } public static function getsomethingstatic() { return $this->someMember * 5; } } $obj = new someClass(); echo $obj::getsomethingstatic(); 

and return an error, I know it has something to do with static but I couldn't find good explanation. I know how to fix this, I'm just looking for an explanation which will add to my understanding.

Anyone?

1
  • $this is an instance reference, and as such cannot be used in a static (non instance) method Commented Aug 20, 2016 at 12:24

2 Answers 2

2

A static function ($obj::) cannot return/use a non-static ($this) class property, you'd have to make getsomethingstatic non-static to return the variable or make the variable static and update your other functions respectively.

As $this refers to the instance in question and static functions by definition are used outside of the instance it is not possible to mix.

ProTip

In the future, please include the error in the OP. It was easy to spot the error in this question but it might not have been in another case so included the required information speeds up the process.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't use the object accessor -> within Static methods. Use the Scope-Resolution Operator :: instead; prefixing it with either self or static as shown below. However be sure to use only static member variables/properties within Static methods as well...

 class someClass { public static $someMember; public function __construct() { self::$someMember = 1; // OR static::$someMember = 1; } public static function getsomethingstatic() { return self::$someMember * 5; // OR return static::$someMember * 5; } } // TO CALL A STATIC METHOD OF A CLASS, // YOU NEED NOT INSTANTIATE THE CLASS... // SIMPLY CALL THE METHOD DIRECTLY ON THE CLASS ITSELF.... echo someClass::getsomethingstatic(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.