Page 1 of 1

My Object variables aren't working - why?

Posted: Wed Mar 31, 2010 3:09 pm
by basementjack
I am trying to learn how to do objects in PHP.
I am getting thrown off in variable scope.

is there a good beginners tutorial on the basics of using objects and variables?

here's the type of issue I'm having:

class test
{
public $myvar;

Function sayhello()
{
echo "Hello $myvar";
}
}

$a = new test();
$a->myvar = "Jack";
$a->sayhello();

fails because of the variable scope.

Re: My Object variables aren't working - why?

Posted: Wed Mar 31, 2010 3:27 pm
by jbulaswad
Jack,

The variable that you are attempting to access below is part of that object's scope, you will need to access it via $this when the method is within the class. See the following example for a point of reference:

Code: Select all

<?php
class test {
	public $myvar;
	function sayhello() {
		echo "Hello {$this->myvar}";
	}
}
$a = new test();
$a->myvar = "Jack";
$a->sayhello();
?>
I also suggest you set your functions as public/private/protected depending on the intended method callee.

My point of reference would be the php manual: http://php.net/manual/en/language.oop5.php.

Perhaps someone else can point you to another 3rd-party reference.

Re: My Object variables aren't working - why?

Posted: Thu Apr 01, 2010 3:15 am
by phu
OO in PHP is not that different from the same in C++ or Java (just a bit more... crippled). It seems you're new to the concept in general... if you're looking to just learn it for PHP, then PHP.net's references/tutorials might help. Otherwise just look for object-oriented programming tutorials or primers; there's no quick way to learn it.

Wikipedia will get you the basic concepts, and can probably link you to nearly-worthless 'hello world' implementations. Go looking for barebones blog or CMS apps, read the code and try to determine what's well-done and what's not; short of having a learned mentor, your own judgment is the best you're likely to find.

Keep an open (but cautious) mind. :)