2

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!

asked Oct 15, 2016 at 12:07
1
  • Replace $this with something else. Commented Oct 15, 2016 at 12:09

2 Answers 2

3

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.

answered Oct 15, 2016 at 12:10

Comments

1

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;

?>`

answered Oct 15, 2016 at 12:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.