
In this article, we learn the best way to create getter and setter strategies in PHP. Getter and setter strategies are utilized when we need to restrict the direct access to the variables by end-users. Getters and setters are methods used to define or retrieve the values of variables, normally private ones.
Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object.
Let's understand the use of getter and setter methods through an example.
<?php
class Person{
private $name;
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$person = new Person();
echo $person->name;
?>PHP Error Cannot access private property Person::$name
In our Person class above, we have a private property called $name. Because it is private property, we are unable to access them directly like the above and that will produce a fatal error.
立即学习“PHP免费学习笔记(深入)”;
动态WEB网站中的PHP和MySQL详细反映实际程序的需求,仔细地探讨外部数据的验证(例如信用卡卡号的格式)、用户登录以及如何使用模板建立网页的标准外观。动态WEB网站中的PHP和MySQL的内容不仅仅是这些。书中还提到如何串联JavaScript与PHP让用户操作时更快、更方便。还有正确处理用户输入错误的方法,让网站看起来更专业。另外还引入大量来自PEAR外挂函数库的强大功能,对常用的、强大的包
508
To run the code above and get our desired output Let's test this example.
<?php
class Person{
private $name;
public function setName($name){
$this->name = $name;
}
public function getName(){
return 'welocme'. $this->name;
}
}
$person = new Person();
$person->setName('Alex');
$name = $person->getName();
echo $name;
?>welcomeAlex
在这里,为了访问我们的私有属性,我们创建了一个名为getData的“getter”函数,因为属性的可见性设置为私有,您也无法更改或修改它们的值。因此,您应该使用我们创建的“setter”函数之一:setName。之后,我们实例化了Person对象。
我们使用我们的setter技术setData将$name属性设置为“Alex”。然后,我们使用我们的getter函数getData检索了$name属性的值。
以上就是PHP中的getter和setter方法是什么?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号