我来到这里的代码:
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");
答案 0 :(得分:3)
是:
public function __construct($content, $author) {
$this->content = $content;
$this->author = $author;
$this->all = "{$this->author} Wrote: {$this->content}";
}
取决于目标的其他方式,但现有代码中如何设置$this->content
和$this->author
?
答案 1 :(得分:2)
对@AbraCadaver的轻微修改(还没有足够的代表添加评论)
public function __construct($content='my default content', $author='my default author') {
$this->content = $content;
$this->author = $author;
$this->all = "{$this->author} Wrote: {$this->content}";
}
我建议这样做,因为看起来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;
}
我更喜欢将变量保密,然后自己构建set并获取公共函数。它为验证和格式化规则留出了空间,以便稍后添加。
答案 2 :(得分:1)
将您的班级成员公开是不好的做法。只有类方法(函数)应该是公共的,即使这样,一些方法也可能受到保护和/或私有。
按照惯例,将您的类成员设置为private或protected,然后通过setter和getters访问它们,并使用带有所需属性的构造函数来实例化文章对象:
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();