Setting the value of a static variable inside a class

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
lfnovo
Forum Newbie
Posts: 2
Joined: Sat Mar 27, 2010 11:13 pm

Setting the value of a static variable inside a class

Post by lfnovo »

Hi everyone, I am trying to use static variables and methods in my PHP Class and I am having some trouble.
None of the options below (case 400 or case 401) is setting the value of $latest_error correctly. I have debugged it nd I am sure that the application is reaching that code. Is there anything wrong in the way I am setting $latest_error? or with the way I am trying to read it?

Here is the page that calls the User Login function.

Code: Select all

if ($_POST["action"] == "login")
{

	$u = User::login($_POST["loginname"], $_POST["password"]);
	
	if (!$u)
	{
		$error = WebError(User::$latest_error);
	}
	else
	{
		//some stuff;
	}
}

Here is my User Class

Code: Select all

class User
{
	
	public static $latest_error;
	
	public static function login($pUsername, $pPassword)
	{		
//some irrelevant code that returns $result
		switch($result->statuscode)
		{
			case 201:
				return new User($result->decodedresult);
				break;
			case 401:
			
				$latest_error = "Login and/or Password not found";
				return false;
				break;
			case 400:
		
				$latest_error = "Please, enter your login and password";
				return false;
				break;
		}
	}
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Setting the value of a static variable inside a class

Post by requinix »

Code: Select all

$latest_error = "Login and/or Password not found";
That creates a variable called "latest_error" inside the function.

If you want the class variable you need $this-> for regular variables and self:: for static variables.

Code: Select all

self::$latest_error = "Login and/or Password not found";
lfnovo
Forum Newbie
Posts: 2
Joined: Sat Mar 27, 2010 11:13 pm

Re: Setting the value of a static variable inside a class

Post by lfnovo »

Worked beautifully. Many thanks.
Post Reply