PHP class arguments in functions

I'm having trouble using an argument from my class in one of these class 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 create an instance (second to last line), the construction magic method works fine and produces "TheNameOfSomething". However, when I call the name () function, I get nothing.

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

Thanks
-Giles
http://gilesvangruisen.com/

+3
source share
2 answers

You need to set the class property with 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();
+11

$name $name , . , , $this->.

$this->name = $name;

. , , script .

$comp = new company();

$comp->name = 'Something';

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

Source: https://habr.com/ru/post/1720980/


All Articles