$this 在 PHP 中意味着什么?

发布于 2024-10-01 08:07:53 字数 219 浏览 5 评论 0原文

可能的重复:
PHP:自我与此

你好, 你能帮我理解 PHP 变量名 $this 的含义吗?

感谢您的帮助。

Possible Duplicate:
PHP: self vs this

Hello,
Could you help me understanding the meaning of the PHP variable name $this?

Thank you for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

坏尐絯℡ 2024-10-08 08:07:53

$this 指的是您所在的班级。

例如

Class Car {

    function test() {
        return "Test function called";
    }

    function another_test() {
        echo $this->test(); // This will echo "Test function called";
    }
}

希望这会有所帮助。

$this refers to the class you are in.

For example

Class Car {

    function test() {
        return "Test function called";
    }

    function another_test() {
        echo $this->test(); // This will echo "Test function called";
    }
}

Hope this helps.

如若梦似彩虹 2024-10-08 08:07:53

您可能想看看 在 PHP5 中,使用 self 和 $this 之间有什么区别?何时合适?

基本上,$this 指的是当前对象。

You might want to have a look at the answers in In PHP5, what is the difference between using self and $this? When is each appropriate?

Basically, $this refers to the current object.

微暖i 2024-10-08 08:07:53

$this 是在对象内使用的受保护变量,$this 允许您在内部访问类文件。

示例

Class Xela
{
   var age; //Point 1

   public function __construct($age)
   {
      $this->setAge($age); //setAge is called by $this internally so the private method will be run
   }

   private function setAge($age)
   {
      $this->age = $age; //$this->age is the variable set at point 1
   }
}

它基本上是一个变量范围问题, $this 只允许在已启动的对象内,并且仅引用该对象及其父对象,您可以运行私有方法并设置私有变量,如外部你不能的范围。

self 关键字也非常相似,除了它指的是 class 中的静态方法,static 基本上意味着你不能使用 $this 因为它不是还没有一个对象,您必须使用 self::setAge(); 并且如果该 setAge 方法被声明为静态,那么您不能从该对象的瞬间调用它/ object

一些供您入门的链接:

$this is a protected variable that's used within a object, $this allows you to access a class file internally.

Example

Class Xela
{
   var age; //Point 1

   public function __construct($age)
   {
      $this->setAge($age); //setAge is called by $this internally so the private method will be run
   }

   private function setAge($age)
   {
      $this->age = $age; //$this->age is the variable set at point 1
   }
}

Its basically a variable scope issue, $this is only allowed within a object that has been initiated and refers to that object and its parents only, you can run private methods and set private variables where as out side the scope you cannot.

also the self keyword is very similar apart from it refers to static methods within class, static basically means that you cant use $this as its not an object yet, you must use self::setAge(); and if that setAge method is declared static then you cannot call it from an instant of that object / object

Some links for you to get started:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文