PHP Query String Variable Parameters - php

I've noticed a lot of PHP functions accept variables like this in any order.
<?php function_name('var8=hi, var2=hello'); ?>
Edit:
Like charles mentioned the string will actually look like this:
<?php function_name('var8=hi&var2=hello'); ?>
If I wanted to write a function like that, how would I do that?

You are just passing that function a string. For it to make any sense of that, it would have to parse the string to split up the key/value pairs. I'm not saying it's the best approach, but if you want to do that, you should use parse_str().
Note that this is not by any means a language feature of PHP, but I am just providing a means to handle what you've shown.

I am confused to as why you have your parameters in quotations.
When you create a function in php you are able to set default values by setting the variable, like so:
<?php
function foo($bar = 'pie')
{
return $bar;
}
echo foo(); // will echo pie
echo foo('bar'); //will output bar
?>

That's not quite a common idiom, but if there is a strong use case and makes your API more usable, why not. Short of using parse_str and the URL-encoded format, you could of course write a mini parser for that.
Pretty simple would also be abusing parse_ini_string for that:
function function_name($paramstr) {
extract(parse_ini_string(strtr($paramstr, ",", "\n")));
You'd probably still want default values; then also needs an array_merge etc.
(The reason this is not widely used is that you end up with only string scalars, and it prohibits the delimiters in the values as well. And not often are an arbitrary number of parameters really useful.)

Related

How to call a function on a variable in PHP?

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 :)

str_replace: Replace string with a function

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().

using 'printf' to return string, not print it

This may sound strange, but here goes.
I like using this technique of building a string in php
printf(__('This is %1$s, this is %2$s'), myFunction1(), myFunction2());
Obviously this directly prints the results whenever the function is called, but I would like to use this technique to just build a string, and then use it later elsewhere.
Is this possible?
Thanks guys.
Use sprintf to do this:
$var = sprintf(__('This is %1$s, this is %2$s'), myFunction1(), myFunction2());

convert $var of function to string?

My goal just debug
function dbg($var){
echo "you have passed $var";
}
call dbg($test)
output:
you have passed test
call dbg("var")
output:
you have passed "var"
In php .anyone could help me to do that?
Try this if $var is a global variable:
function dbg($var){
echo "you have passed {$GLOBALS[$var]}";
}
Well, the second case is fairly straightforward - you're passing a string and you want to display the string. No worries.
But for the first case, I'm afraid the answer is: No you can't.
Once inside the function, PHP doesn't know anything about the variable that was passed into it other than the value.
I can't really see that it would be of much value though. It would be trivial to change your code to pass in a name and a value -- ie something like this:
function dbg($name,$value) {
print "You passed $name, and the value was $value";
}
dbg('test',$test);
That's not really all that great either though -- you may as well just use print_r() and friends.
If you really want more powerful debugging tools, you should look into xDebug. It's a proper debugging tool for PHP, which allows you to step through the code line-by-line, and see the contents of variables at any point during the program run (among many other good features). It also integrates nicely with several popular IDEs.

How to make a natural String class in PHP

Hai. I was making this simple string class and was wondering if there was a more natural way of doing it.
class Str{
function __construct($str){
$this->value = $str;
$this->length = strlen($str);
..
}
function __toString(){
return $this->value;
}
..
}
so now i have to use it like this:
$str = new Str('hello kitty');
echo $str;
But that doesnt look very 'natural' with the parentheses. So i was wondering if something like this, or similar was possible.
$str = new Str 'hello kitty'; # I dont believe this is possible although this is preferred.
$str = new Str; # get rid of the construct param.
$str = 'value here'; #instead of resetting, set 'value here' to Str::$value??
In the second method, is there a way i could possibly catch that variable bing set again and instead of reseting it, set this to Str::$value ? I have thought around and the closest i could come up to is the __destruct method. but there was no possible way to know how it was being destroyed. Is this possible or am i wasting my time?
Since PHP is loosely typed, there is no natural string class, because the natural way of using strings is, well, by just using them. However, as of PHP5.3 there is an extension in the SPL that provides strongly typed scalars:
http://php.net/manual/en/book.spl-types.php
However, keep in mind that this extension is marked experimental and subject to change. As of now, it is also not available on Windows.
You might also want to try https://github.com/nikic/scalar_objects
This extension implements the ability to register a class that handles the method calls to a certain primitive type (string, array, ...). As such it allows implementing APIs like $str->length().
Also See: https://github.com/alecgorge/PHP-String-Class
A good string class
It's impossible to call functions in PHP without parentheses.
Your next method will change the reference to string.
Why it doesn't look natural to you? It's the same way in Java.
You may find this useful:
php-string
I'm afraid to tell you that you won't have any luck with either of both.
$str = new Str 'hello kitty'; will end up in fatal error and though the second method is valid it doesn't do what you intend but rather reassign a native string.
May I ask why you would want to have a wrapper araound a native type?

Categories