I am having to do:
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
I want to avoid that redundant mention of the variable name. I tried:
htmlspecialchars_decode(&$sourceElement['description']);
and
call_user_func('htmlspecialchars_decode', &$sourceElement['description']);
That did not work. Is this possible in PHP? Call a function on a variable?
You could create your own wrapper function that takes the variable by reference:
function html_dec(&$str) {$str = htmlspecialchars_decode($str);}
Then call:
html_dec($sourceElement['description']);
The correct solution would be to include that "redundant" variable mention. It's far more readable, and far less confusing that way.
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
Your way of thinking is good though, you're thinking how to shorten your code, like a true lazy programmer =)
It depends on function. htmlspecialchars_decode() returns the result, it doesn't modify the original variable. And you can do nothing about it.
Most functions in PHP are immutable in mature, i.e. they don't modify the arguments you pass into them. This has a few advantages, one of them being able to use their return value in expressions without side effects.
Here's a generic wrapper you could use to mimic mutable behaviour for any function that takes a single argument:
function applyFn(&$s, $fn)
{
return $s = $fn($s);
}
applyFn($sourceElement['description'], 'htmlspecialchars_decode');
applyFn($sourceElement['description'], 'trim'); // trim string
Mileage may vary :)
Related
I have a little issue with deleting a part of string using php.
Let me get you a little bit into problem, I have vlariable "column1text" in which is text string endered into < textarea >, but that does not matter. I want to remove all HTML tags from this string since they are doing problems sometimes. For example: When this string contains < /body > or < /table > it will do a lot of unwanted mess. So I want to get these tags away.
I am using $column1text = str_replace("TEXT TO REMOVE", "", $column1text); and it works, but I want to make function for it (optionaly if you know easier way, just tell me, I'll be glad).
I am using this function:
function remove($removetext)
{
$column1text = str_replace($removetext, "", $column1text);
}
And I am using it like this:
remove("TEXT TO REMOVE");
What am I doing wrong? (I am sure it's something pretty silly, but I cannot find it!)
P.S. I am totally sorry about my English, it must sound stupid, but I had no other idea than asking you.
You can either pass in $column1text as reference, or have your function returns the modified text (which I prefer)
function remove($column1text, $removetext) {
return str_replace($removetext, "", $column1text);
}
$column1text = remove($column1text, '<span>');
You are passing by value, when you actually need to be passing by reference. If you don't know what the difference is I suggest reading up a little on it.
Link
edit:
In a nutshell, whenever you pass a function a parameter, that function makes a copy of whatever it was passed, so when that parameter is manipulated in the function, it manipulates the copy and not the passed object itself.
When a function has a parameter passed by reference, then it actually has access to the object that was passed itself. That means anything you do to manipulate that object also affects the object outside of the function (since its not just a copy of it you are working with).
You need to tell interpreter that you want to use global variable, because now it sees it as local variable (within your function). To do this you just need to use global keyword:
function remove($removetext) {
global $column1text;
$column1text = str_replace($removetext, "", $column1text);
}
you can read more about it here http://php.net/manual/en/language.variables.scope.php
$myVar=myFunction(array_reverse(explode('.', $_SERVER['SERVER_NAME'])));
Anything wrong with nesting functions like this?
This is ok as long as you can guarantee that each function will always return the desired type. For instance if a function might return a FALSE value, it may be cast to an unexpected value.
The example provided works because both explode (as called) and array_reverse will both always return an array.
A counter-example:
mysqli_query(mysqli_connect(...), 'INSERT INTO tbl VALUES ....');
Since mysqli_connect may return a resource OR FALSE it shouldn't be chained like this. The return value should always be checked for correctness.
It's totally valid to do this, but keep it readable. If you nest 15 function calls or nest a handful of function callss with several parameters each, you'll have an intensely unfun debugging experience.
No it is perectly valid to do that
It may be a bad practice because it makes the code harder to understand and therefore to maintain.
A good practice to overcome this problem is to comment your code (heavily).
People nest functions like that all of the time. Functions are meant to be used in this way. Since functions can return a value, it is, therefore, meaningful to assign a variable to a function, to get the value of that function into a PHP variable.
Thank god for functions returning values, otherwise, it would be a mess to think of it the other way...
Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().
To simplify escaping strings using mysql_real_escape_string I was hoping to be able to write a function that would take an arbitrary number of arguments and apply the function to them all.
Something like this:
function escape()
{
$args = func_get_args();
array_map('mysql_real_escape_string', $args);
}
As you should be able to see, this would rely on the arguments being passed to this function as references. Given that call time references can't be done in PHP anymore what's the best workaround to this? As I have a not insignificant number of functions that write specific subsets of info to the database I really need a generic function like the above rather than having calls to mysql_real_escape_string everywhere.
My testing has also indicated that arguments passed to mysql_real_escape_string are always passed by value. So even if I could get a reference to escape() my hard work is subsequently destroyed. Is there any way around this?
There must be other people with a similar use case out there but maybe the solution is to just call the function directly. At least I can wrap mysql...... in a function with a shorter name to keep the code cleaner. This may just be a situation where PHP has no equivalent to being able to pass a pointer.
The short answer is, it's not pretty.
The long answer is:
function escape_all(array $args) {
foreach($args as &$arg) {
$arg = mysql_real_escape_string($arg);
}
}
escape_all(array(&$foo, &$bar));
This is stumping me.. I am writing components / library functions where it would be used for calling a lot of different functions, so I want it to make an array print out each variable to be passed into the function as an argument, like below but I am pretty sure that this isn't proper syntax.. thanks for any advice
$myfunction = function_name;
$myfunction (print_r($my_array));
You can use a built-in php function, reference from call-user-func-array
In addition to Bang Dao's answer:
If you need to get all function arguments as array, use func_get_args().