views:

225

answers:

2

Hi,

I'm having trouble using an argument from my class in one of that class's functions.

I have a class called company:

class company {

   var $name;

   function __construct($name) {
      echo $name;
   }

   function name() {
      echo $name;
   }
}

$comp = new company('TheNameOfSomething');
$comp->name();

When I instantiate it (second to last line), the construct magic method works fine, and echos out "TheNameOfSomething." However, when I call the name() function, I get nothing.

What am I doing wrong? Any help is greatly appreciated. If you need any other info, just ask!

Thanks
-Giles
http://gilesvangruisen.com/

+7  A: 

You need to set the class property using the $this keyword.

class company {

   var $name;

   function __construct($name) {
      echo $name;
      $this->name = $name;
   }

   function name() {
      echo $this->name;
   }
}

$comp = new company('TheNameOfSomething');
$comp->name();
David Caunt
Awesome! Works perfectly. Thanks so much!
Giles Van Gruisen
A: 

When using $name in either method, the scope of the $name variable is limited to the function that it is created in. Other methods or the containing class are not able to read the variable or even know it exists, so you have to set the class variable using the $this-> prefix.

$this->name = $name;

This allows the value to be persistent, and available to all functions of the class. Furthermore, the variable is public, so any script or class may read and modify the value of the variable.

$comp = new company();

$comp->name = 'Something';

$comp->name(); //echos 'Something'
davethegr8