My Object variables aren't working - why?

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
basementjack
Forum Newbie
Posts: 2
Joined: Tue Feb 02, 2010 9:28 pm

My Object variables aren't working - why?

Post 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.
jbulaswad
Forum Newbie
Posts: 14
Joined: Tue Mar 30, 2010 2:37 pm
Location: Detroit, Michigan, USA

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

Post 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.
phu
Forum Commoner
Posts: 61
Joined: Tue Mar 30, 2010 6:18 pm

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

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