Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: is $this->something->($this->foo)->bar legal?

Tags:

php

mongodb

Is this line legal PHP?

$this->mongo->($this->db)->$collection_name->insert($document_name);

if $this->db is a constant with the db name to use.

Thank you

like image 330
CamelCamelCamel Avatar asked Jan 13 '11 18:01

CamelCamelCamel


2 Answers

Try using curly braces instead of parentheses:

$this->mongo->{$this->db}->$collection_name->insert($document_name);

Or assigning $this->db to a local var and using that instead:

$db_name = $this->db;
$this->mongo->$db_name->$collection_name->insert($document_name);
like image 158
BoltClock Avatar answered Oct 05 '22 15:10

BoltClock


No, strings (and thus your constant) should be wrapped in brackets, like this:

$this->mongo->{$this->db}->$collection_name->insert($document_name);
like image 45
Richard Tuin Avatar answered Oct 05 '22 14:10

Richard Tuin