Php 在类中设置默认变量
我得到了这个密码:Php 在类中设置默认变量,php,class,object,Php,Class,Object,我得到了这个密码: class Article { public $content,$author, $all; public function __construct() { $this->all = "{$this->author} Wrote: {$this->content}"; } } $newArt = new Article(); $newArt->content = "Lorem ipsum"; 这很好,但我的问
class Article {
public $content,$author, $all;
public function __construct() {
$this->all = "{$this->author} Wrote: {$this->content}";
}
}
$newArt = new Article();
$newArt->content = "Lorem ipsum";
这很好,但我的问题是:
在设置新类时,是否有任何方法可以自动设置该值?比如:
$newArt = new Article("content of content variable", "author");
是的:
其他方法取决于目标,但是如何在现有代码中设置$this->content
和$this->author
其他方法取决于目标,但是如何在现有代码中设置
$this->content
和$this->author
?对@abracadver进行轻微修改(还没有足够的代表添加评论)
我建议这样做是因为OP看起来不需要构造参数。通过这种方式,可以在不传递任何内容的情况下对其进行实例化,如果不传递任何内容,则默认为一些预定义的值
另一种办法是:
public function __construct() {
$this->content = 'my default content';
$this->author = 'my default author';
$this->all = "{$this->author} Wrote: {$this->content}";
}
然后使用如下函数在以后设置值:
public set_author ($author) {
$this->author = $author;
}
我更喜欢保持变量私有,然后自己构建集合并获取公共函数。它为以后添加验证和格式规则留出了空间。对@abracadver进行了轻微修改(还没有足够的代表添加注释) 我建议这样做是因为OP看起来不需要构造参数。通过这种方式,可以在不传递任何内容的情况下对其进行实例化,如果不传递任何内容,则默认为一些预定义的值 另一种办法是:
public function __construct() {
$this->content = 'my default content';
$this->author = 'my default author';
$this->all = "{$this->author} Wrote: {$this->content}";
}
然后使用如下函数在以后设置值:
public set_author ($author) {
$this->author = $author;
}
我更喜欢保持变量私有,然后自己构建集合并获取公共函数。这为以后添加验证和格式规则留出了空间。将类成员设置为公共成员是不好的做法。只有类方法(函数)应该是公共的,甚至有些方法可能是受保护的和/或私有的 按照惯例,将类成员设置为私有或受保护,然后通过setter和getter访问它们,并使用具有所需属性的构造函数来实例化文章对象:
class Article{
private $content;
private $author;
private $all;
public function __construct($content, $author){
$this->content = $content;
$this->author = $author;
$this->all = "{$this->author} wrote: {$this->content}";
}
public function getAll{
return $this->all;
}
}
然后,您可以在客户端脚本中调用此类:
$article = new Article('Lorem Ipsum', 'William Shakespear');
echo $article->getAll();
把你的班级成员公之于众是不好的做法。只有类方法(函数)应该是公共的,甚至有些方法可能是受保护的和/或私有的 按照惯例,将类成员设置为私有或受保护,然后通过setter和getter访问它们,并使用具有所需属性的构造函数来实例化文章对象:
class Article{
private $content;
private $author;
private $all;
public function __construct($content, $author){
$this->content = $content;
$this->author = $author;
$this->all = "{$this->author} wrote: {$this->content}";
}
public function getAll{
return $this->all;
}
}
然后,您可以在客户端脚本中调用此类:
$article = new Article('Lorem Ipsum', 'William Shakespear');
echo $article->getAll();
击败我:)这里也有一些信息:击败我:)这里也有一些信息: