Simple PHP class question

I have a simple question regarding PHP classes.

Several times I saw other frame classes, etc., using method calls.

$post->data->text(); 

I like this functionality and not just something like this.

 $post->dataReturnAsText(); 

But I'm not quite sure how they created this functionality to have a “sub-method”? Hope someone can point me in the right direction ....

+4
source share
3 answers

There is nothing special in the above example:

 <?php class Post{ public $data; } class Data{ public function text(){ } } $post = new Post; $post->data = new Data; $post->data->text(); 

However, you probably found it in the context of the method chain (very popular in JavaScript libraries):

 <?php class Foo{ public function doThis(){ return $this; } public function doThat(){ return $this; } } $foo = new Foo; $foo->doThis()->doThat()->doThis(); 
+2
source

In this case, the data is simply an attribute of the class and contains another object:

 class data { public function text() { } } class thing { public $data; } $thing = new thing(); $thing->data = new data(); $thing->data->text(); 
0
source

perhaps it’s just that the “data” is a public property of $ post containing the wth object, for example, the text property:

 class Textable { public $text; function __construct($intext) { $this->text = $intext; } } class Post { public $data; function __construct() { $data = new Textable("jabberwocky"); } } 

this will allow you to do:

 $post = new Post(); echo( $post->data->text ); // print out "jabberwocky" 

Of course, the correct way to OOP is to make the property private and allow access using the getter function, but beyond the point ...

0
source

All Articles