dongyi2159 2016-10-02 15:36
浏览 54
已采纳

PHP中$ this的真正定义是什么?

I currently am using PHP and was reading the PHP manual but still have a problem with $this.

Is $this something global or is it is just another variable name to build objects on?

Here is an example:

public function using_a_function($variable1, $variable2, $variable3)
{
    $params = array(
        'associative1' => $variable1,
        'associative2' => $variable2,
        'associative3' => $variable3
    );
    $params['associative4'] = $this->get_function1($params);
    return $this->get_function2($params);
}

How would $this work for the return function? I guess I am confused on how this function builds. I understand building the associate array part with a name being a valuekey names => value, but $this throws me off on this example.

  • 写回答

2条回答 默认 最新

  • douju1365 2016-10-02 15:57
    关注

    It is refered to as the Object scope, lets use an example class.

    Class Example
    {
        private $property;
        public function A($foo)
        {
             $this->property = $foo;
             // we are telling the method to look at the object scope not the method scope
        }
        public function B()
        {
             return self::property; // self:: is the same as $this
        }
    }
    

    We can now instance our object and use it in another way also:

    $e = new Example;
    $e::A('some text');
    // would do the same as
    $e->A('some other text');
    

    This is just a way of accessing the scope of the Object because methods cannot access other method scopes.

    You can also extend a class and use the parent:: to call the class extension scope, for example:

    Class Db extends PDO
    {
        public function __construct()
        {
            parent::__construct(....
    

    Which would access the PDO construct method rather than its own construct method.

    In your case, the method is calling other methods that are in the object. Which can be called using $this-> or self::

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!