dongtan4046 2014-06-25 14:56
浏览 190
已采纳

访问类中私有/受保护变量的正确方法(PHP)

What is the proper way of accessing private/protected variable in a class in PHP?

I learned that it can be access using __construct function. Ex.

class helloWorld
{
    public $fname;
    private $lname;
    protected $full;
    function __construct()
    {
        $this->fname = "Hello";
        $this->lname = "World";
        $this->full = $this->fname . " " . $this->lname;
    }
}

Or create a Getter or Setters function. I don't know if that's the right term.

class helloWorld
{
    public $fname;
    private $lname;
    protected $full;

    function getFull(){
        return $this->full;
    }

    function setFull($fullname){
        $this->full = $fullname;
    }

}

or via __toString. I'm confuse o what should I use. Sorry, I'm still new to OOP. Also what is :: symbol in php and how can I use it?

Thanks :)

  • 写回答

2条回答 默认 最新

  • duanlu4371 2014-06-25 15:31
    关注

    :: operator is called the scope resolution operator. It has a no.of use case.

    1.Can be used to refer static variables or function of a class . the syntax is class name::variable_name Or class name::function_name() . This is because static variables or functions are referenced through class names .

    2.It can also be used for function overriding. You can understand it with an example

    class Base
    {
        protected function myFunc() {
            echo "I am in parent class 
    ";
        }
    }
    
    class Child extends Base
    {
        // Override parent's definition
        public function myFunc()
        {
            // But still call the parent function
            Base::myFunc();
            echo "I am in the child class
    ";
        }
    }
    
    $class = new Child();
    $class->myFunc();
    

    This is useful when you want your parent function to be executed first and then your child function.

    3.It is also used to refer the variables or functions within a class itself through self::$variable_name OR self::function_name() . Self is used to refer to the class itself.

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

报告相同问题?

悬赏问题

  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!