declaring instance variables

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
the_cheat
Forum Newbie
Posts: 5
Joined: Tue Oct 12, 2010 4:09 pm

declaring instance variables

Post by the_cheat »

I can't find anything about this, I just want to know if this is a valid line:

Code: Select all

private $var1, $var2, $var3;
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: declaring instance variables

Post by cpetercarter »

Yes.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: declaring instance variables

Post by s.dot »

Yes, it is a valid line.

They will be declared but their values will be NULL.. therefore running isset() on them will return FALSE. Interestingly enough, a non-declared variable will have the same value as a declared variable.

check out this code

Code: Select all

<?php

class varTest
{
	private $a, $b, $c;
	
	function isVarSet($var)
	{
		return isset($this->$var);
	}
	
	function otherTest($var)
	{
		var_dump($this->$var);
	}
}

//object
$varTest = new varTest();

//see what's in it
var_dump($varTest);

//check if isset()
var_dump($varTest->isVarSet('a'));
var_dump($varTest->isVarSet('b'));
var_dump($varTest->isVarSet('c'));

//check undeclared variable
$varTest->otherTest('d');
and result
[text]object(varTest)#1 (3) {
["a:private"]=>
NULL
["b:private"]=>
NULL
["c:private"]=>
NULL
}
bool(false)
bool(false)
bool(false)
NULL
[/text]
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply