函数中的 PHP 类参数 [英] PHP Class arguments in functions

查看:26
本文介绍了函数中的 PHP 类参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在该类的函数之一中使用来自我的类​​的参数时遇到问题.

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

我有一个班级叫公司:

class company {

   var $name;

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

   function name() {
      echo $name;
   }
}

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

当我实例化它时(倒数第二行),construct 魔法方法工作正常,并显示TheNameOfSomething".但是,当我调用 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!

谢谢
-贾尔斯
http://gilesvangruisen.com/

推荐答案

您需要使用 $this 关键字设置类属性.

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

这篇关于函数中的 PHP 类参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆