how a variable can be accessed inside a static method?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
webspider
Forum Commoner
Posts: 52
Joined: Sat Oct 27, 2007 3:29 am

how a variable can be accessed inside a static method?

Post 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( )?
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post 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...
User avatar
webspider
Forum Commoner
Posts: 52
Joined: Sat Oct 27, 2007 3:29 am

Post 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?
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

well it's just different behaviour. frequently static is overused...and leads to problems..so it really depends...
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post 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.
Post Reply