Page 1 of 1

Newbie in PHP

Posted: Sun Feb 11, 2007 8:56 pm
by ngolehung84
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have this code block:

Code: Select all

class A
{
	var $loc; 
	function A($val)
	{
		$loc = $val;
	}	
}

$obj = new A(5);
echo $obj->loc;
When it execute, it doesnot display anything. Can you explain?
Thanks,
Hung.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Sun Feb 11, 2007 9:00 pm
by wildwobby
to start make it $this->loc instead of just $loc here:

class A
{
var $loc;
function A($val)
{
$loc = $val;
}
}

$obj = new A(5);

Posted: Mon Feb 12, 2007 1:07 am
by james.aimonetti
If you are using PHP5, I think it is more proper to declare member variables using public / private / protected. http://www.php.net/manual/en/language.oop5.php outlines the functionality and code used in creating classes with PHP5. For PHP4, see http://www.php.net/manual/en/language.oop.php to educate yourself on the implementation of OOP there, which differs in some respects from PHP5's implementation. Personally, I'd be sure PHP5 was being used if you have control over that decision.

Posted: Mon Feb 12, 2007 2:24 am
by CoderGoblin
For PHP5 the following will work

Code: Select all

class A
{
        var $loc;

        public function __construct($value)
        {
           $this->loc=$value;
        }

        public function getLoc()
        {
                return $this->loc;
        }

        public function setAndGetLoc($value)
        {
               $this->loc=$value;
               return $this->getLoc();
        }        
}

$obj = new A(5);
echo $obj->getLoc(); // returns the value of the constructor (5)
echo $obj->getAndSetLoc(8); // Changes the Loc value and returns it.
An alternative is

Code: Select all

class A
{
        var $loc;

        public function __construct($value)
        {
           $this->loc=$value;
        }

        public static function getLoc($value)
        {
                $loc=$value;
                return $loc;
        }       
}

echo A::getLoc($value);
One of the primary things you will notice is that the class methods return something, as a normal function can. This is the value you are setting, in your case an echo to. This is same in PHP4 and PHP5.

Hop that helps