Solved

Inline PHP function call

Posted on 2016-07-31
13
58 Views
Last Modified: 2016-08-01
I want to be able to call a PHP function inline .. the only way I know is:

class i { function r($c) { return $c; } } global $i; $i = new i();

$string = "hello {$i->r(myfunction())} world";

Of course I can do $string = "hello ".myfunction().' world' but I prefer a shorter way

Any suggestions?
0
Comment
Question by:Mark
  • 6
  • 4
  • 3
13 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41736706
Can you step back a little from the technical details and tell us in plain language why you want to do this?  I know of no modern design pattern that rewards compound statements -- to the contrary, they are generally considered antipractices.  It makes sense to package functionality in classes and methods, but compound statements are hard to understand, modify, test and debug, so professionals avoid things like that.  Maybe if we can understand your objectives we can offer a few good ideas.
1
 

Author Comment

by:Mark
ID: 41736709
When performing SQL insert/update statements, I perform string escapes (I have thousands of lines of code not using PDO and not going to upgrade it).
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 41736711
I agree with Ray, I would Never do that.  You should keep in mind that PHP 'preprocesses' your code and puts it in a condensed format that will execute properly.  While it won't normally change the order of execution, it will optimize it in ways you don't see.  Write code you can easily understand.  Let PHP take care of optimizing it.
1
 

Author Comment

by:Mark
ID: 41736712
I don't want compound statements either but I don't want my code looking like

"INSERT INTO x SET x='".escape($a)."'.....
0
 

Author Comment

by:Mark
ID: 41736713
I prefer "INSERT INTO x SET x='{$f->escape($a)}'"; ...

I guess what I'm asking is if I can call the escape function like
"INSERT INTO x SET x='{escape($a)}'"
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 41736717
I don't see any difference between them and I would still not do that.  I always break it into two lines.  First line creates the variable value and the second line uses it.  Let PHP optimize it.

Besides, why aren't you using the mysql_real_escape functions that are recommended?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41736718
if I can call the escape function like
"INSERT INTO x SET x='{escape($a)}'"
PHP syntax is not really well constructed for that.  You might consider using arrays of key=>value pairs, where the key is the column name and the value is the information you want to inject into the column.

You might consider refactoring the application.  It would  be easier than trying to get all those queries right one-at-a-time.  A database abstraction layer (which is what PDO gives you) can be a very helpful thing.  A design that uses the active record pattern, like Symfony or Laravel, makes database interaction very easy, without introducing complicated syntax.

Some of this article might be helpful:
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
0
 

Author Comment

by:Mark
ID: 41736719
My user defined function escape calls mysql_real_escape_string ...

I appreciate the advice but it's just not practical at the moment .. is there anyway to call a function within a quoted string ...
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41736726
is there anyway to call a function within a quoted string ...
Not that I know of, at least not in modern PHP, and that kind of coding is discouraged by all the modern designs.  PHP used to allow this for some things, but it's been removed from the language.  An abstraction layer is a better idea.  You can extend the PDO or MySQLi classes to produce your own abstraction layer, making one that is easier to adapt for your existing code.

Might be worth looking into E-E Gigs for some in-depth hands-on help.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 41736731
My own code looks exactly like this.  On hundreds of pages.
$username2 = $link->real_escape_string($username);
$updsql = "INSERT INTO `users` (`username`) VALUES ('$username2');";
$updrslt = $link->query($updsql);

Open in new window

0
 

Author Comment

by:Mark
ID: 41736732
This seems to work ...

function foo($p) { return $p; }

$_ = function($param) { return $param; };

echo "Does this appear? {$_(foo('yes'))}.";

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 41737310
I guess we're back to "what are we trying to achieve" here.  

Examples using echo may or may not give you exactly what you want when you try to extend the examples to generate escaped SQL query strings.  PHP echo has been around a long time and isn't really constrained by modern programming ideas.  It does some things that violate rules of other parts of PHP, which makes it a poor test case for our ideas.  A better test case can be created with var_dump() which in my experience always tells the truth.  To see why this matters, use echo to print out an array (not one element, but the whole array).  Similar tripwires exist throughout PHP because of its silent type juggling and loose comparisons.

Here is an example of how PHP can be confusing.  You can install this on your server and run it, then try it again by removing the comment marks on line 33.  The programming looks very much the same, but the semantic values are dramatically different.  This is the sort of thing that makes for late nights, tears and sadness.  Highly compressed source code has the same dreary effects on our lives.
<?php // demo/broken_constant.php
/**
 * How to write confusing programming.  Don't do this sort of thing.
 *
 * http://php.net/manual/en/language.types.string.php
 * http://php.net/manual/en/function.define.php
 */
echo '<pre>';


// THE DEFAULT PHP ERROR REPORTING SUPPRESSES "NOTICE" MESSAGES
// error_reporting(E_ALL);


// MODIFIED EXAMPLE 8 FROM PHP Strings MAN PAGE
$juices =
[ "apple"
, "orange"
, "koolaid"     => "purple"
, "lemon"       => "Yellow"
, "dragonfruit" => "Oxblud"
]
;
echo PHP_EOL . "He drank some $juices[0] juice";          // apple
echo PHP_EOL . "He drank some $juices[1] juice";          // orange
echo PHP_EOL . "He drank some $juices[koolaid] juice";    // purple
echo PHP_EOL . "He drank some $juices[lemon] juice";      // Yellow
echo PHP_EOL . "He drank some {$juices["lemon"]} juice";  // Yellow
echo PHP_EOL;


// ACTIVATE THIS TO CHANGE THE MEANING OF "lemon"
// define("lemon", 'dragonfruit');

echo PHP_EOL . "He drank some  $juices[lemon]  juice";    // Yellow -- DOES NOT USE THE DEFINED CONSTANT
echo PHP_EOL . "He drank some {$juices[lemon]} juice";    // Yellow or Oxblud? -- MIGHT USE THE DEFINED CONSTANT
echo PHP_EOL . "He drank some {$juices["lemon"]} juice";  // Yellow -- USES THE STRING LITERAL INDEX
echo PHP_EOL;

// WHAT DO YOU SUPPOSE THIS WILL PRINT?
$thing = lemon;
echo PHP_EOL . "He drank some  $juices[$thing]  juice";   // GUESS, THEN TEST
echo PHP_EOL . "He drank some {$juices[$thing]} juice";   // GUESS, THEN TEST
echo PHP_EOL . "He drank some {$juices["$thing"]} juice"; // GUESS, THEN TEST
echo PHP_EOL;

// WHAT DO YOU SUPPOSE THIS WILL PRINT
$thing = lemon;
$tdata = $juices[$thing];
var_dump($tdata);
echo PHP_EOL;

// WHAT DO YOU SUPPOSE THIS WILL PRINT
$thing = "lemon";
$tdata = $juices[$thing];
var_dump($tdata);
echo PHP_EOL;

Open in new window

The purpose of any programming language is to help us write better programs.  PHP can do that, but only if you're careful to respect the design of PHP.

The purpose of any program is to communicate ideas to (1) computers and (2) people.  This is why the principle of least astonishment is important.  The computer doesn't really care how nicely you write and format your code, or whether the function and variable names make sense.  Those things are the choices we make for the people who will read our code -- our fellow programmers, or ourselves, if we have been away from the code for more than a few days, and come back to work on it again.

So when the question becomes, "How can I make my code more compact?" my experience tells me we are asking the wrong question.  The right question is usually "How can I make my code more readable, easier to extend and reuse, easy to read and understand, etc?"  This is one of the main reasons that professional programmers choose IDEs like PHPStorm.  If you need a hundred parallel changes to make your code more readable, it does this kind of thing automatically, at the touch of a button.  You don't have to make a hundred programming changes - the IDE will do that for you!  Good IDEs let us think about the software design that solves problems instead of the minutiae of whether I can stuff more meanings into a single line of code.  

Choose whatever works best for you, and best of luck with your project!
0
 

Author Closing Comment

by:Mark
ID: 41737387
Thank you
0

Featured Post

Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

Join & Write a Comment

this article is a guided solution for most of the common server issues in server hardware tasks we are facing in our routine job works. the topics in the following article covered are, 1) dell hardware raidlevel (Perc) 2) adding HDD 3) how t…
In this article we have discussed the manual scenarios to recover data from Windows 10 through some backup and recovery tools which are offered by it.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now