Click to See Complete Forum and Search --> : The hidden functionality of PHP
weekender
07-04-2005, 07:13 PM
Hi folks
I'm planning on writing a guide to hidden functionality within php; the features, functions and code which are not immediately obvious from code examples or in the manual.
These are, by definition, things i am only just stumbling upon, and so I need your help to make the list more definitive.
I currently have;
The Ternary Operator
echo (isset($name)) ? "Name is set" : "Name is not set";
I didn't find this for ages - it's not on the if page, and not obvious on the comparison operators (http://uk2.php.net/operators.comparison) page, unless you scroll to the bottom.
Type Casting/Juggling
$number = (int) "13";
Some might argue that you don't need to type cast variables, as php automatigally juggles between them - but i'm convinced that one day i will, and besides - it's good practice.
__FILE__ and __LINE__
error_log("[__FILE__][__LINE__]");
Simply put, global variables that store the current file and line being parsed. Useful in error logging.
apache_note
apache_note('session_id', session_id());
Allows getting/setting of variables between the different phases of an apache GET request. For instance, allows php to pass variables (such as the session id) to the logging module, so you can track sessions in your apache logs.
"here doc" echo syntax
echo <<<END
Here is a block of code, which can contain $variables to be parsed.
END;
Not quite sure where this comes from, guess it's an old perl survivor or something. Useful for outputting large amounts of text.
Pre- and post-increments
$counter = 5;
echo $counter++; // outputs 5
$counter = 5;
echo ++$counter; // outputs 6
If you put the ++ before the variable, the variable is incremented and then echoed. If you put the ++ after, the variable will not change until after the echo.
Anyway, that's where i'm up to at the moment - and there must be loads more. I hope this snares your curiosity; your homework is to go out there and find more examples. Oh, needless to say i'll make every effort to credit replies in the final article.
Cheers, Adam
Edited to add a few i forgot!
planetsim
07-04-2005, 08:48 PM
Im not sure about post-increments being hidden infact that was the first thing I was taught that existed within PHP.
However the pre-increment I didnt know about for a little while.
Probably also hidden the variable variables.
$myvar = "variable";
${$myvar} = "this is a string";
echo $myvar."\n".$variable;
/*
outputs
------------------
variable
this is a string
*/
And simple substr to access single chars
$string = "String";
echo $string{2}; //outputs r
Thats all that comes to mind.
halojoy
07-04-2005, 09:59 PM
Originally posted by weekender
Hi folks
I'm planning on writing a guide to hidden functionality within php;
Cheers, AdamVery good, Adam.
thank you.
I know half of them, but any day you have put your guide
somewhere for online reading or ZIPPED html download
I'll be first one to get a copy of Your Guide.
halojoy of sweden
:)
Drakla
07-04-2005, 11:19 PM
You can grab the raw post data sent to a script with$data = file_get_contents('php://input');which you can hack up yourself if necessary - and is if somebody has named a load of form elements with the same name.
The Magic Constants __FUNCTION__, __CLASS__ and __METHOD__ also exist, the latter only in php 5. __FUNCTION__ is also good for debugging. As is get_defined_vars()
weekender
07-05-2005, 06:40 AM
Thanks guys, all good stuff. I'll add the following
Variable variable names
Simple char access
The Magic Constants
Getting raw input data
keep em coming!
Sgarissta
07-05-2005, 10:27 AM
$var = "test";
$$var = "hello world";
echo $test;
Weedpacket
07-05-2005, 10:45 AM
for($i=0,$j=1; $i<20; $i++,$j<<=1)
{
echo $i,' ',$j,"\n";
}
Not too useful in the middle part, which decides when the loop terminates because only the rightmost condition is used to decide the outcome.
bradgrafelman
07-05-2005, 11:57 AM
Probably also hidden the variable variables.
To expand on this subject a bit, you can combine strings and multiple variables too, like so:
$prefix = 'var_';
$suffix = '_test';
${$prefix . 'Something' . $suffix} = 'Hello world.';
echo $var_Something_test; // Hello world.
vaaaska
07-05-2005, 12:32 PM
Wonderful thread! :)
Shrike
07-05-2005, 01:12 PM
From an object oriented perspective of PHP 4
// Passing and returning by reference - the reference operator &
$foo =& new Foo;
foo( $foo, 'test' );
function &foo( &$obj, $value )
{
$foo->bar = $value;
return $foo;
}
// Static function variables (and the Singleton)
function &getSingletonInstance()
{
static $instance;
if( !is_object( $instance ))
{
$instance = new Class;
}
return $instance;
}
weekender
07-05-2005, 05:31 PM
Thanks everybody, i'm really stoked by all the responses! There are a couple i don't really get without further attention, but i'll be sure to contact the posters' if i still struggle after a bit of reading.
I'll hopefully get around to writing the article at the weekend or early next week. I was going to put it up on my site, and possibly try and get it stickied here - i'll let you all know.
Keep the ideas coming!
bubblenut
07-05-2005, 07:21 PM
Embeding complex variables in strings with braces.
$string = "something with a {$object->parameter['element']} variable in it";
weekender
07-05-2005, 07:26 PM
Good one bubble!
I'll prob put that in the same bit with the difference between single and double quotes to surround values; being that single parse faster, but won't parse embedded variables
$drink = 'milk';
echo 'I drink $drink'; // I drink $drink
echo "I drink $drink"; // I drink milk
Drakla
07-05-2005, 08:14 PM
You might as well do variable functions if you're doing variables<?php
function bold_me($val)
{
return '<b>'.$val.'</b>';
}
function huge_me($val)
{
return '<h1>'.$val.'</h1>';
}
$str = 'What you looking at?';
$funky = 'huge_me';
echo $funky($str);
$funky = 'bold_me';
echo $funky($str);
?>
I wrote about variable variables not long ago - you can see that operator precidence is important, so brackets are needing if you're creating some names - http://phpbuilder.com/board/showthread.php?s=&postid=10635438#post10635438
Is knowing how to similate static class variables in php4 worth knowing about, or is that all old hat now?
Drakla
07-06-2005, 01:44 AM
Ok, one more thing, as I finally got this working today. I've tried to run a php script in the background kicked off from a webpage... no problem, but the browser never knows it's time to stop, so keeps sitting there. I sort of solved it by kicking off another script with shell exec'ing the script, but also wanted the happy, simple one shot deal... and here it is<?php
/* Got a good feeling about this one - used connection closed a few times in
* experiments... now adding the content size:
* IT WORKS!
*/
set_time_limit(120);
ignore_user_abort(true); // not actually needed anymore!
ob_start(); // ALL content must be captured so the length can be passed on
for ($i = 0; $i < 20; $i++)
{
echo "I'm talking... $i<br />";
}
header('Connection: close');
header("Content-length: ".ob_get_length());
ob_end_flush(); // fly my pretties!
flush(); // browser should now stop rolling
echo "If you can see this your browser is ignoring the content length and I'm crying again.";
error_log('Time before sleep: '.date('H:i:s')."\n", 3, 'run-in-says.txt');
sleep(60);
echo "WHY YOU STILL HERE!!!!!!!"; // you won't see this
error_log('Time AFTER sleep: '.date('H:i:s')."\n", 3, 'run-in-says.txt');
error_log('Con status post sleep: '.connection_status()."\n", 3, 'run-in-says.txt');
?>
Don't know if 'running in the background' would be part of your hidden functionality being as you can do it with cron jobs or my exec way... but I've being trying to suss it for aaaages, and so have others.
weekender
07-06-2005, 05:24 AM
Thanks Drakla - i was actually going to put set_time_limit and ignore_user_abort in the list.
Now how to organise the guide? I think three sections;
Code syntax
Useful constants
Individual functions
More complex 'recipes'
BuzzLY
07-06-2005, 10:49 AM
I think first, you learn how to count. :p
weekender
07-06-2005, 12:11 PM
har bloody har.
thanks buzz, i'll remember to credit you in the final article for that
bradgrafelman
07-06-2005, 01:08 PM
If you start using interesting functions, don't forget to check if they have a dependency (such as a .dll/.so (or whatever the Unix extension is) and be sure to mention that, otherwise someone might spend hours tinkering with something in your guide only to find out they had to uncomment the ";extension=" line!).
suepahfly
07-07-2005, 01:10 PM
I beleive there's a function witch will autmaticly add and string to the urls in the output buffer (like the sessions handler does using url based sessions). Only i don't know the name of the function. I think it must something like
addUrl("var=$val"); or something.
devinemke
07-07-2005, 02:56 PM
i often see people using REGEX and strstr for simple string searches. this is a more efficient way:
$haystack = 'this is a string with a needle in it';
if (strpos($haystack, 'needle') !== false) {echo 'needle was found';}
else {echo 'needle was NOT found';}
bradgrafelman
07-07-2005, 03:04 PM
I 100% agree with devinemike. I myself had been doing very very nasty searches such as this:
if(eregi('something', $lotOfText) {
or making replacements such as:
$something = eregi_replace('foo', 'bar', $something);
If you're doing simple searches, and don't need REGEXP (if you don't even know what REGEXP, or Regular Expression is, then this point is emphaiszed even more), do not use any ereg_ or preg_ functions! Instead, use functions such as strpos or str_replace.
IF you must use regular expression, learn PCRE regex syntax (http://www.php.net/manual/en/reference.pcre.pattern.syntax.php) instead of POSIX regex syntax (http://www.php.net/manual/en/ref.regex.php[/URL). PCRE's syntax not only has more features, but is faster, too!
Drakla
07-07-2005, 05:28 PM
Originally posted by suepahfly
I beleive there's a function witch will autmaticly add and string to the urls in the output buffer (like the sessions handler does using url based sessions). Only i don't know the name of the function. I think it must something like
addUrl("var=$val"); or something.
Yeah output_add_rewrite_var I found that the other day and wondered if I'd ever have to use it.
davidjam
07-08-2005, 04:19 PM
$selected[$page->data[$this->unique_key][($this->key."_num")]] = .. // "embedded" values
if($_POST[$$key->required_if] != ${$$key->required_if}->ignore_value) { .. } // more variable variable fun!
${"_".$row['design_name']} = $row['rgb']; // this one already mentioned
I guess the break-through for me (well one of them!) was understanding the order and manner in which php evaluates things. Recommended reading for everyone: expressions (http://www.php.net/manual/en/language.expressions.php). Post and pre-incrementing also discussed on this page. :)
PHP Builder
Copyright WebMediaBrands Inc. All Rights Reserved.