0

So I'm reading some documentation on Drupal, and I come across this example:

$result = db_select('contact', 'c')
    ->fields('c')
    ->execute()
    ->fetchAssoc();

Now, I get that you're assigning the result from a function to the $result variable, but why are there arrows after this? Those are normally used to refer to the properties of an object, if I recall correctly - is that what is going on here? That doesn't seem like it would make sense to me though. This may be ignorance on my part though - but I'm not seeing any documentation on this specific effect.

How should I be reading this example?

Steven Matthews
  • 8,255
  • 33
  • 98
  • 186

4 Answers4

2

It's just a more readable way of writing:

$result = db_select('contact', 'c')->fields('c')->execute()->fetchAssoc();
Blender
  • 257,973
  • 46
  • 399
  • 459
2

Yes, this is a property of an object.

db_select('contact', 'c') returns an object, which has a method "fields", which returns an object, which has a method "execute" and so on...

result of "fetchAssoc()" method on the resulting object of "execute()" on the resulting object of the "fields()" run on the resulting object of the "db_select()" is actualy stored in $result.

new line symbols do not change antything, there are used only for clarity, interpreter ignores them.

lejlot
  • 56,903
  • 7
  • 117
  • 144
1

What you see is a method call on the return value of each of those methods. Instead of storing each return value in a variable often methods get chained like this.

Bart
  • 16,076
  • 5
  • 54
  • 79
1

This is not specific to Drupal, and can be done if the Objects (thus classes) involved have been written to allow it.

$result = db_select('contact', 'c')
    ->fields('c')
    ->execute()
    ->fetchAssoc();

is exactly:

$result = db_select('contact', 'c');   // $results is now a SelectQuery object
$result = $results->fields('c');       // $results is now a ???
$result = $results->execute;           /* $results is now a DatabaseConnection_mysql 
                                          object, which you can loop over, to return 
                                          individual results */
$result = $results->fetchAssoc();      // $results is now an associative array

And the reason you can chain those lines as in the first code is because each method returns something (which is an object) that the next method can work on (the object class has that method).

Nabil Kadimi
  • 8,870
  • 2
  • 46
  • 54