0

Simple question, is it possible to access a static variable from a $this-> call?

class testA { public static $var1 = "random string"; // current solution public function getVar() { return self::$var1; } } class testB { private $myObject; public function __construct() { $this->myObject = new testA(); // This line is the question echo $this->myObject::var1; // current solution echo $this->myObject->getVar(); } } 

I'm afraid I've answered my own question. But having a few static variables I didn't want to have a function for each variable, Or even a single getVar($staticVar) when I could access it directly.

If this is the only solution. Any recommendations on a better way to implement this.

If I'm going to require a function call for each, I might as well get rid of the static variables altogether.

//method public function staticVar1() { return (string) 'random string'; } 
1
  • Yes that is correct. I think I need to walk away from the computer for an hour. Take a break :) Commented Feb 14, 2014 at 3:07

2 Answers 2

1

You simply access the variable like this:

testA::$var1; 

So using your exemple, it would be

class testB { private $myObject; public function __construct() { $this->myObject = new testA(); // This line is the question echo testA::$var1; // current solution echo $this->myObject->getVar(); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Oh yeah duh. Something I probably could have answered if someone else asked the question. Talk about over thinking it. Thanks.
It happens to everyone ^^
1

Try to understand the purpose of static.

static makes them accessible without needing an instantiation of the class.

They should accessed as below if the static variable is in the class

self::$var1; 

below is possible in your case

testA::$var1; 

would do the job here.

3 Comments

Thanks but self::$var1; is incorrect as it's being accessed outside the class. You updated your answer as I was commenting though. testA::$var1; would do the trick.
I have mentioned the both scenarios so you can get an idea about it
Yeah I appreciate that for anyone else with the same question. It was just a brain dead moment. As stated earlier. Gave you an up vote for it anyway :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.