我有一个关于PHP类的简单问题。
我多次看到其他类框架等使用方法调用,如。
$post->data->text();
我喜欢这个功能,而不是仅仅做这样的事情。
$post->dataReturnAsText();
但我不太确定他们是如何创建这个功能的,也许有一个"子方法"?希望有人能给我指路....
您提供的示例没有什么特别之处:
<?php
class Post{
public $data;
}
class Data{
public function text(){
}
}
$post = new Post;
$post->data = new Data;
$post->data->text();
然而,你可能在方法链(在JavaScript库中非常流行)的上下文中发现过它:
<?php
class Foo{
public function doThis(){
return $this;
}
public function doThat(){
return $this;
}
}
$foo = new Foo;
$foo->doThis()->doThat()->doThis();
在这种情况下,data只是类的一个属性,它包含另一个对象:
class data
{
public function text()
{
}
}
class thing
{
public $data;
}
$thing = new thing();
$thing->data = new data();
$thing->data->text();
这可能只是一个"data"是$post的一个公共属性,包含一个对象与文本属性,例如:
class Textable {
public $text;
function __construct($intext) {
$this->text = $intext;
}
}
class Post {
public $data;
function __construct() {
$data = new Textable("jabberwocky");
}
}
这将允许你做:
$post = new Post();
echo( $post->data->text ); // print out "jabberwocky"
当然,正确的OOP方法是将属性设为私有并允许使用getter函数访问,但除此之外。