1

I have below scenario, want to use specific method as static so can i use $this for other methods or not.

class foobar { public $foo; public function __construct() { global $foo; $this->foo = $foo; } public static function foobarfunc() { return self::foo(); } public function foo() { return $this->foo = 'hi'; } } echo foobar::foobarfunc(); 

ERROR:

Fatal error: Using $this when not in object context in

This is my scenario

class DB{ public function selectQuery(){ $data = $this->finddata(); return "SELECT $data FROM bhumi"; } public function finddata(){ $data = ('*'); return $data; } } class TP extends DB{ public static $create; public function __construct(){ $this->parentObj = new DB(); } public static function printQ(){ $d = parent::selectQuery(); return $d; } } echo TP::printQ(); 

How to do that? this code giving me error.

9
  • What is the error? Commented Feb 28, 2018 at 13:00
  • "this code giving me error." What error? Commented Feb 28, 2018 at 13:00
  • return self::foo(); <-- foo() isn't static. You need to create an instance first Commented Feb 28, 2018 at 13:00
  • what if I don't want to create an instance. Commented Feb 28, 2018 at 13:04
  • Why using static to return result of classical instance ? make no sens.. Commented Feb 28, 2018 at 13:06

3 Answers 3

1

When you dont want to create an instance, ignoring the reasons why:

<?php class foobar { public static $foo; public function __construct() { global $foo; $this->foo = $foo; } public static function foobarfunc() { return self::foo(); } public static function foo() { return self::$foo = 'Hi!';; } } echo foobar::foobarfunc(); ?> 
Sign up to request clarification or add additional context in comments.

1 Comment

is this correct way or another answer one?
1

try this way

public static function foobarfunc() { $foobar = new self(); return $foobar->foo(); } 

2 Comments

is this correct way or another answer one?
@BhumiShah I think this answer makes more sense in whatever you're trying to do, since you can keep your foo() method non-static.
0
public static function foobarfunc() { return self::foo(); } 

You just want to load another static method called "foo". This method exist and is not static, so the error is valid.

You can fix it with

public static function foobarfunc() { $instance = new self(); return $instance->foo(); } 

Albeit, the usefullness of this use be left open.

2 Comments

is this correct way?
@BhumiShah There is no "correct" way. It all depends on what you need to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.