Giles Van Gruisen
Giles Van Gruisen

Reputation: 961

PHP Class arguments in functions

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/

Upvotes: 4

Views: 15825

Answers (2)

davethegr8
davethegr8

Reputation: 11595

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'

Upvotes: 1

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58361

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();

Upvotes: 16

Related Questions