PHP Class arguments in functions

12,080

Solution 1

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

Solution 2

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'
Share:
12,080

Related videos on Youtube

Giles Van Gruisen
Author by

Giles Van Gruisen

Design, Objective-C, JavaScript, Ruby

Updated on April 19, 2022

Comments

  • Giles Van Gruisen
    Giles Van Gruisen about 2 years

    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/