在PHP中的类中访问私有/受保护变量的正确方法是什么?
我了解到可以使用__construct
功能进行访问。前任。
class helloWorld
{
public $fname;
private $lname;
protected $full;
function __construct()
{
$this->fname = "Hello";
$this->lname = "World";
$this->full = $this->fname . " " . $this->lname;
}
}
或创建一个Getter
或Setters
函数。我不知道这是不是正确的名词。
class helloWorld
{
public $fname;
private $lname;
protected $full;
function getFull(){
return $this->full;
}
function setFull($fullname){
$this->full = $fullname;
}
}
或通过__toString
。我感到困惑,我该怎么用。抱歉,我还是OOP的新手。另外什么是::
php中的符号,我该如何使用它?
谢谢 :)
:: operator
被称为scope resolution operator
。它有一个用例编号。
1.可用于引用类的静态变量或函数。语法为class name::variable_name
Or class 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_name
OR引用类本身中的变量或函数self::function_name()
。Self用于引用类本身。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句