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


Proper way of accessing private/protected variables in a class (PHP)

在PHP中访问私有/受保护变量的正确方法是什么?

我了解到可以使用__construct函数访问。交货。

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

或创建GetterSetters函数。我不知道这个词是否正确。

class helloWorld
{
    public $fname;
    private $lname;
    protected $full;
    function getFull(){
        return $this->full;
    }
    function setFull($fullname){
        $this->full = $fullname;
    }
}

或通过__toString。我不知道该用什么。对不起,我对OOP还是个新手。还有什么是::符号在php和我如何使用它?

谢谢:)

最好定义公共getter和setter,并且只使用它们来获取和设置类属性。然后让所有其他函数使用这些getter和setter来集中管理属性。

:: operator称为scope resolution operator。它有一个no。用例的。

1。可用于引用类的静态变量或函数。语法为class name::variable_nameclass name::function_name()。这是因为静态变量或函数是通过类名引用的。

2。它也可以用于函数重写。你可以用一个例子

来理解它
class Base
{
    protected function myFunc() {
        echo "I am in parent class 'n";
    }
}
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'n";
    }
}
$class = new Child();
$class->myFunc();

当你想先执行父函数后执行子函数时,这很有用。

3。它还用于通过self::$variable_nameself::function_name()引用类本身中的变量或函数。Self用来引用类本身