My code is like below:
<?php
class ClassName {
private $data = null;
public function __construct($data) {
$this->data = $data;
}
public static function staticFun ($data) {
echo $this->anotherFun($data);
}
private function anotherFun ($data) {
return $this->data;
}
}
?>
I am trying to call ClassName::staticFun('nilya');
as staticFun
is a static function but I get Fatal error: Using $this when not in object context
error. I know the distinction between static and non-static methods and how to call them but, in above code the given error occurs.
Is it possible to call a non-static method in a static method? If not how should the code be modified to make it work?
Thanks in advance!
2 Answers 2
Just create an instance:
public static function staticFun ($data) {
$instance = new ClassName($data);
echo $instance->anotherFun($data);
}
Note: you have a parameter $data
for anotherFun
, but you don't use it anywhere.
Comments
Use Bellow Code You can call another function from static function.
In Static method $this Not Working So First we create Object of current Class.
`
class ClassName {
private $data = null;
public function __construct($data) {
$this->data = $data;
}
public static function staticFun ($data) {
$call = new ClassName($data);
$value = $call->anotherFun($data);
return $value;
}
private function anotherFun ($data) {
return $this->data;
}
}
$obj = new ClassName("vajram");
$valueget = $obj->staticFun("phaneendra");
echo $valueget;
?>`
$this
with something else.