Reputation: 10390
Why does this return a "strict standard" notice?:
'Strict Standards: Non-static method main::i() should not be called statically in...'
class main
{
public function __construct()
{
echo "in main class";
}
public function i()
{
echo "i in main";
}
}
class secondary extends main
{
public static function tom()
{
parent::i();
}
}
secondary::tom();
I am legally calling a static method which contains a call to a non static method in a parent class.
Upvotes: 0
Views: 678
Reputation: 5524
class main
{
public function __construct()
{
echo "in main class";
}
public static function i()
{
echo "i in main";
}
}
class secondary extends main
{
public static function tom()
{
parent::i();
}
}
secondary::tom();
Is what it should look like, notice I have converted the function i();
to a static, which then can legally be called by parent::i();
But performing:
public static function tom()
{
$this->i();
}
Will return:
Fatal error: Using $this when not in object context
So your bet is to go fully static, or not static.
A resolution:
class main
{
public function __construct()
{
echo "in main class";
}
public function i()
{
echo "i in main";
}
}
class secondary extends main
{
public function tom()
{
$this->i();
}
}
$Class = new secondary();
$Class->tom();
Upvotes: 0
Reputation: 9200
You've already answered the question yourself - while you're calling tom()
statically (which is fine), i()
is not static.
Being non-static i()
assumes that you have an instance of the object, and therefore could be trying to access properties or perform other actions which require an instance. As such it shouldn't be called statically, not even from within a static method in a child class. Consider for example the following slight change to your code:
class main
{
var something = 0;
public function __construct()
{
echo "in main class";
}
public function i()
{
$this->something++;
echo "i in main";
}
}
class secondary extends main
{
public static function tom()
{
parent::i();
}
}
secondary::tom();
It's a strict warning - meaning you can choose to ignore it if you want to - but it's informing you that what you're doing is not generally good practice and you should probably rethink your approach.
Upvotes: 0
Reputation: 160923
The notice is telling you should not call a non static method within a static method.
You could check the method i()
, if $this
doesn't appear in that method, you may consider change i()
to static method.
Upvotes: 3