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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办