douhensheng1131 2017-12-15 12:54
浏览 13
已采纳

何时使用$ this和简单变量

I'd like to create the class that should manage my log. I begin to write this class. And I don't know when to use $this and when simple variable. Here is the code.

<?php
    class Log{
        private $name = "record.log";

        public function create($this->name){
            $handle = fopen($this->name, "a+");
            fclose($handle);
        }
    }

Or should I use only $name instead of $this->name?

  • 写回答

1条回答 默认 最新

  • duanfan5012 2017-12-15 13:10
    关注

    In OOP:
    $this->name is property of the object which is defined by the class and is accessible globally within the object.
    $name is variable used inside the class method and is accessible locally only within the object method (a function)

    Very briefly:

    class myClass{
    
        private $name = "record.log";
    
        function myMethod(){
          $name = 'this exists only in the method myMethod()';
          $this->name; // this contains the 'record.log' string
        }
    
    }
    

    From outside the class you cannot access the variable $name defined within an object.

    You can only access the property $name defined in the class but from outside of the object you must call it using the object name:

    $obj = new myClass();
    $log_file = $obj->name; // this would contain the string 'record.log'
    

    However you defined the object property as private so the direct access will be restricted from outside of the object. To be able to access it you have to define getter/setter a methods that will handle read/write to private property.

    // add to the class methods
    public function getName(){
      return $this->name;
    }
    
    public function setName($value){
      // do some validation of the value first
      //...
      // then assign the value 
      $this->name = $value; 
    }
    

    So now you can access the object property $name from outside of the object using statements:

    echo $obj->getName();  // prints record.log
    $obj->setName('new.log');
    echo $obj->getName();  // prints new.log
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错