What does the variable $this mean in PHP?

2018-12-31 11:45发布

I see the variable $this in PHP all the time and I have no idea what it's used for. I've never personally used it, and the search engines ignore the $ and I end up with a search for the word "this".

Can someone tell me how the variable $this works in PHP?

标签: php oop this
9条回答
旧时光的记忆
2楼-- · 2018-12-31 12:44

Lets see what happens if we won't use $this and try to have instance variables and constructor arguments with the same name with the following code snippet

<?php

class Student {
    public $name;

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

$tom = new Student('Tom');
echo $tom->name;

?>

It echos nothing but

<?php

class Student {
    public $name;

    function __construct( $name ) {
        $this->name = $name; // Using 'this' to access the student's name
    }
};

$tom = new Student('Tom');
echo $tom->name;

?>

this echoes 'Tom'

查看更多
无色无味的生活
3楼-- · 2018-12-31 12:45

It's a reference to the current object, it's most commonly used in object oriented code.

Example:

<?php
class Person {
    public $name;

    function __construct( $name ) {
        $this->name = $name;
    }
};

$jack = new Person('Jack');
echo $jack->name;

This stores the 'Jack' string as a property of the object created.

查看更多
余欢
4楼-- · 2018-12-31 12:45

$this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

查看更多
登录 后发表回答