Reputation: 4161
I am wondering whether it is possible to call functions on string literals (Like in Python) in PHP (Tried googling, but 90% sure my terminology is off).
Example python:
"test,1,2,3".split()
I want to achieve something like (In php psuedo code):
$result = "SELECT `db`.`table`.`field` FROM `db`.`table` WHERE 1"->query();
Currently I am doing this:
$result = MySql::query("SELECT `db`.`table`.`field` FROM `db`.`table` WHERE 1");
But I really like the simplicity of the middle example and was wondering if anything like that is possible in PHP, maybe by overriding the PHP string class?
Upvotes: 0
Views: 823
Reputation: 521995
The difference is that everything in Python (and similar OO languages) is an object, that's why even strings have "methods" and "properties". PHP isn't a full top-to-bottom OO language, strings are just primitive strings. Even if they were objects, a string probably wouldn't have methods pertaining to database queries, because that'd be quite weird OO design with terribly mixed responsibilities.
Upvotes: 4
Reputation: 31614
There's no real way to do what you're talking about
$result = "SELECT `db`.`table`.`field` FROM `db`.`table` WHERE 1"->query();
In this example, your string is just a string. You then try to reference it like an object. In this case, you would get a Fatal
error because you're telling PHP to use an object where none exists.
The closest thing to what you describe is direct chaining, where you create an instance of the class and reference it in the same statement (available in PHP >= 5.4)
$class = (new Class())->function();
Upvotes: 2