This question already has answers here:
Are PHP short tags acceptable to use?
(28 answers)
Closed 8 years ago.
I sort of discovered by accident that
<?php ... ?>
can be shortened to
<? ... ?>
Is this a bad idea? In some cases? What cases are they? Are there anymore shorthand examples? I am aware of shorthand examples involving conditional statements but I don't find them easier to read.
Please link me if this has been answered elsewhere, but I could not find it via a search. Maybe I'm not using the right keywords.
This shorthand has been available for a very long time, but its use is discouraged (and nowadays disabled by default) because of various incompatibilities with other languages — ambiguity with ASP's ability to accept <? x ?>, and with various XML constructions, are two obvious examples.
Opt not to use it.
By contrast, the <?= x ?> shorthand (equivalent to <?php echo x ?>) has had a resurgence in popularity and is enabled by default since PHP 5.4, because it does not suffer from the same problems.
As always, consult the documentation for canonical information on such things.
The shorthand tags are only enabled in certain setups. They are discouraged. See the PHP manual entry for the tags: http://www.php.net/manual/en/language.basic-syntax.phptags.php
PHP also allows for short open tags (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.
As far as other shorthands, no others exist. The <?= ?> shorthand could possibly be considered one, though it's only usage is to output a variable (as mentioned in another answer to this question). The omission of the closing ?> is sort-of one. It's handy for documents that contain nothing beyond PHP code. This technique is also mentioned in the manual entry I linked above.
Will it work? In some cases. PHP has a few opening tags available, take a look here. But you should be careful as it depends on the php configuration (usually /etc/php.ini or /etc/php/php.ini). There is an option short_open_tag = On. if it's not enabled, the code will be rendered in the view and won't be executed as php code.
As blakeo_x said, the shorthand is only valid if the PHP configuration file has it enabled.
It is discouraged because you might have to run it on a different server where shorthand is not enabled. Hence try to stick to the longer version <?php instead.
Related
We have a large codebase, and every so often a var_dump used for testing and not removed/commented suddenly appears out of nowhere. There is a messy solution using XDebug (http://devzone.zend.com/1135/tracing-php-applications-with-xdebug/), but maybe there's something ingenous that can be done in PHP at runtime.
Also, I don't want to modify or search code via regex. I've tried using my own var_dump_v2, but it falls out of use quickly.
Is it possible to use the disable_functions operation in php.ini to disable var_dump on your production server? I am not sure what the outcome of this setting is (ie does it fail with an error, or silently) the documentation is not so clear.
http://php.net/manual/en/ini.core.php - see "disable_functions"
Also there is override_function:
<?php
override_function('var_dump', '$a', 'return 0;');
?>
http://php.net/manual/en/function.override-function.php
There are actually ways to do this, if you have PECL available and runkit installed. You kan make runkit able to overide PHPs internal functions if you in php.ini set runkit.internal_override to "1".
For removing the var_dump function, you could use:
runkit_function_remove('var_dump');
In your case, not to get an error, you should probably instead use something like this:
runkit_function_redefine('var_dump', '','');
Take a look at the runkit extensions documentation here.
You may also want to take a look at "Advanced PHP debugger", another extension that seems to offer an override_function().
You can use monkey patching.
Just defines a namespace on the first line of your file and defines the function var_dump
<?php
namespace monkey;
function var_dump($obj) {}
Of course, it implies that you do not use a namespace in your current file
You could use the function var_dump() prefixing it with the root namespace(): \var_dump()
Of course, all others native function will continue to work as usual as long as you do not override them in your namespace.
Why don't you use serialize() or json_encode() if you have a large database? That will be very useful.
But take note, serialize() will give you a 1-line output somewhat like this:
's:0:"";s:5:"value";'
So you need to learn the anatomy of serialize() to use it: PHP Serialize
I have something like:
if(isset($_POST['submit']))
{
$linktitle=strtolower(str_replace(" ","-",$title));
etc.
$linktitle and $title are actually variables from $_POST - ie $_POST['linktitle'] and $_POST['title'].
Somehow, even though (as far as I can see!) I haven't extract()ed $_POST at this stage in the code, it is still working - PHP is understanding that $title is referring to $_POST['title']. Could anyone please explain why this might be?
Thanks!
ps. Sorry, but I really can't get this inline code quote formatting thing to work...!
register_globals is enabled in your PHP instance. See here for more info.
This is behaviour that should be relied upon as it's use is now deprecated. You will find that you can still use $_POST['keyname'] as well as $keyname, and that is what you should refer to in your code.
Your php.ini file must have register_globals enabled, so GPC variables are being added to the symbol table. This is why you see this behaviour. See the security risks of such a feature here
You have register globals activated in your webserver (php.ini), so PHP replace the unknoe variables with the corresponding GET or POST value. This option is deprecated and dangerous! Disable it if you can!
Is there a way to remove function alias in PHP?
I can rename my function but it would be nice to use name "fetch".
Problem:
I just tested the following code and it appears to work for me, but perhaps it is because I don't have the mysqli library installed. I would test it because it might be more contextual than your IDE will have you believe. It seems to be a method for mysqli, but it might not be a global function.
<?php
function fetch(){
echo 'Hello world!';
}
fetch();
No.
(Short of recompiling the PHP binary)
This is more of a function of the IDE than the actual language... Some IDEs may give you that ability... I don't even know if recompiling the PHP binary (as Alan Storm suggested) would help since sometimes the stuff is hardcoded into the IDE / use the PHP docs online
For completeness sake: Normally, no, this can not be done. However: this can be done using a PECL extension called "runkit".
Runkit is described as "For all those things you probably shouldn't have been doing anyway", and allows you to basically tear out the innards of PHP from within PHP itself. Replacing built-in functions, undefining constants, unloading classes - suddenly everything is possible. And you should really question what you are doing if you ever feel you need it - odds are what you are doing violates some principles that are there for very good reasons, you just don't know them yet. I've never found a situation where using Runkit was a genuinely Good Idea.
Oh, in order to remove built-in functions you'll specifically need to enable this capability in your php.ini
(have fun!)
I've just upgraded to PHP 5.3 and started supporting an old website for a new client. It seems to use rather odd PHP code which I've not come across before.
Whilst trying to access $_GET or $_REQUEST variables, the developer has used the following: ${"variable_name"}
I get notices generated due to undefined variables (presumably because PHP is not parsing the ${"variable_name"} style code).
Changing this to $_REQUEST['variable_name'] works as expected, but I can't go through all their code and change it as the site is massive and uses proprietry layout methods.
Does anyone know if it's possible to switch on support for these tags / codeblocks? I've taken a look in PHP.ini and there is a mention of ASP style tags and short tags but enabling these has no effect (they look totally different anyway, I just thought it was worth a shot).
I don't think there is anything new with that syntax :
$a = 10;
var_dump(${"a"});
Works just fine ;-)
You problem is probably due to the fact that, before, register_globals was enabled (by default, if PHP <= 4.something), and is now disabled -- and that is good for security !
With register_globals set to On, any variable in $_REQUEST is automatically injected as a vartiable in your application -- well, actually, this depends on the variables_order configuration option, but this one almost always includes Get, Post, and Cookie, at least.
For instance, if there is a variable like $_GET['my_var'], you will also have a $my_var variable... And this one can also be accessed with the syntax ${'my_var'}
Considering register_globals is Off by default since something like PHP 4.2, and should disappear in PHP 6 (if I remember correctly), I would advise against re-activating it... at least, if you have the time required to correct / test the code...
Curly brace syntax for variables is an embedded part of PHP, and has been around for quite awhile. The reason it exists is to resolve ambiguities with arrays and object syntaxes when using variable variables.
From the manual:
In order to use variable variables
with arrays, you have to resolve an
ambiguity problem. That is, if you
write $$a1 then the parser needs to
know if you meant to use $a1 as a
variable, or if you wanted $$a as the
variable and then the 1 index from
that variable. The syntax for
resolving this ambiguity is: ${$a1}
for the first case and ${$a}1 for
the second.
It's a very handy syntax in several situations, such as using array or object variables while outputting something using heredoc syntax.
I won't reiterate the advice by others about using register_globals, I just wanted to expound on this unusual syntax.
The ${"variable_name"} syntax is practically the same as $variable_name, except that the contents of the curly braces are evaluated first. It is supported by all recent versions of PHP, even the beta versions. What is not supported by recent versions of PHP though is the support of registering $_REQUEST (and other) variables as global variables. There's a setting for enabling it:
register_globals = on
It is NOT recommended for production use because of security issues though. It may be easier to run you source through some 'sed'-like tool and replace the usages with regular expression.
The old server probably has REGISTER_GLOBALS on. So the weird brackets aren't the problem.
REGISTER_GLOBALS puts all the variables in $_REQUEST as regular variables in the global scope, meaning you can access $_REQUEST['test'] can be accessed like $test or ${"test"}
The bracket syntax is on by default, and I don't believe you can turn it on/off.
register_globals was likely switched on. {$variable_name} syntax is always on, but register_globals turns things like $_REQUEST['variable_name'] into $variable_name.
Avoid switching it on if at all possible, though - there's a reason it's been long advised against, and it's going away entirely in PHP6.
register_globals is deprecated as of php 5.3 and will be removed as of php 6.0. What you want to do is use the Refactoring feature found in most PHP IDE's (zendo studio 6+) to rename the variable to something more appropriate, ie $_GET['variable_name'].
Is there any speed difference between these two versions?
<?php echo $var; ?>
<?=$var?>
Which do you recommend, and why?
Performance difference is insignificant. Moreover, with use of APC, performance difference is zero, null, nada.
Short tags are problematic within XML, because <? is also markup for XML processing tag. So if you're writing code that should be portable, use the long form.
See short_open_tag description in http://www.php.net/manual/en/ini.core.php
Technically the parser has to parse every character of the longer version, and there's a few more characters for every transfer.
If your webserver doesn't "pre-compile" (ie: cache tokenized PHP pages) then there is a slight performance difference. This should be insignificant except, perhaps, when you start talking about billions of runs.
Performance wise it is insignificant.
Proper usage says to use the longer one, as it is more portable. Personally? I do the shorter one.
No, they are identical. If you like typing a lot use <?php echo $var; ?>, otherwise just save time with <?=$var?>.
Which do you recommend
Neither, unless you really want to allow HTML injection. (99% of the time, you don't.)
<?php echo htmlspecialchars($var); ?>
Or define a function that does echo(htmlspecialchars($arg)) with a shorter name to avoid all that typing.
in php 5.3 short tag ASP-style <% %> support will be deprecated, try to avoid this and rewrite the code to the '<?php echo' format, because u cant use <?xml ?> inline for example.
These two lines of code are identical.
I'm adding a late answer because nobody has demonstrated this yet, but the answer is unequivocally no, there is no performance difference specifically because there is no difference at all in how PHP executes these two lines of code.
The interpreter sees the identical code in both cases. The parser produces the exact same AST, because <?= is fundamentally identical to <?php echo. There is no difference in the instructions the interpreter runs when you write <?= vs <?php echo.
By installing php-ast you can examine the AST produced by both lines of code.
Given these two cases...
# CASE 1
<?php echo $i %>
# CASE 2
<?= $i ?>
The abstract syntax tree for both is identical:
case 1
AST_STMT_LIST
0: AST_ECHO
expr: AST_VAR
name: "i"
case 2
AST_STMT_LIST
0: AST_ECHO
expr: AST_VAR
name: "i"
This means PHP cannot tell the difference between these at run time, never mind experiencing some kind of performance difference.
The code to produce this output is as follows, and uses util.php:
<?php
require('util.php');
echo "case 1\n";
echo ast_dump(ast\parse_code('<?php echo $i ?>', $version=50));
echo "\n";
echo "case 2\n";
echo ast_dump(ast\parse_code('<?= $i ?>', $version=50));
echo "\n";
Optimization is irrelevant here. The choice comes down to personal preference, especially since <?= is always available, has nothing to do with short tags, has never been deprecated and is not slated to be removed from the language.
I think the second one requires the short_open_tag (in PHP.ini) to be set to true.
Meaning there is a chance it's turned off on some webservers.
The speed difference depends on how fast you can type those 9 extra characters.
It can also improve the readability of your code, but this is debatable.
If your talking about execution-speed there is no noticable difference.
Don't try to optimize with these, it's useless. Instead, deactivate allow_short_tags (because of problems when loading XML files) and write clean, readable and understandable code.
Even if there may be a slight difference (which is definitely lower than 10%), it's useles to optimize with it. If your scripts are slow, look at your loops first. Most of the time you can win a lot more performance by optimizing the programms flow than by using strange syntax.