Page 1 of 1

how a variable can be accessed inside a static method?

Posted: Wed Dec 26, 2007 5:09 am
by webspider

Code: Select all

<?php
error_reporting(E_ALL | E_STRICT);

class A
{
   	var $a = 10;
	
	function nonstaticmethod()
	{
	  echo "a = $this->a ";   
	}
	
	static function staticmethod()
	{
	  echo "a = $a";   
	}
}

$a = new A;
$a->nonstaticmethod();
A::staticmethod();
?>
how I can access variable $a inside function staticmethod( )?

Posted: Wed Dec 26, 2007 5:36 am
by jmut
you should either assume it is static or not. And use it either Class::$var or $this->var Using php5 and E_ALL | E_STRICT will make you do it right...

Posted: Wed Dec 26, 2007 6:29 am
by webspider
Thanks for your reply.
you should either assume it is static or not.
That means we can not use a non-static variable within a static method. Now I use static before $a and changed my code in following way:

Code: Select all

<?php
error_reporting(E_ALL | E_STRICT);

class A
{
   	static $a = 10;

	function nonstaticmethod($c)
	{
	   echo $c;   
	}
	
	static function staticmethod()
	{
	  echo "a =".A::$a;
	} 
	
	function getA()
	{
	  return A::$a;
	}
}

$a = new A;
$c = $a->getA();
$a->nonstaticmethod($c);
$a->staticmethod();

?>
I am learning OOP in php :) Thanks again for your help.

Edit : I am wondering is there any reason why to use static method? any special advantages using static method over non-static method?

Posted: Wed Dec 26, 2007 8:12 am
by jmut
well it's just different behaviour. frequently static is overused...and leads to problems..so it really depends...

Posted: Wed Dec 26, 2007 10:46 am
by Ambush Commander
In C++, static gives you a slight performance benefit, because with it you promise not to access any of the instance's member variables. In PHP, the syntax for static and regular is different, so really if you're going to call the method like $a->, it should not be static.