Related
I've got 2 files (settings1.php and settings1.default.php) that contain settings variables for a website. When the site's files are updated, its pushed to Github so others can download and use the template site too. Obviously I don't want anyone to download my settings1.php file that contains MySQL database info and other personal info, and I don't want settings1.php to be wiped out when doing a git pull, so I have settings1.default.php that I update as I add new features.
An excerpt of the file is:
<?php
$apikey = "11111111111111";
$TZ = "Europe/London";
$UTC = "1";
$lon = 0.2;
$lat = 50.1;
?>
My goal is to have a PHP script that (quickly) checks if each variable in settings1.default.php exists within settings1.php, and for each variable that doesn't exist, it copies that variable over including its default value. And if the entire settings1.php file is missing, it copies settings1.default.php to settings1.php. The script would need to contend with users adding blank lines between variables, or reordering the variables.
I've hacked out a script that, in a very messy way, does this, but only if there are no blank lines, and only if every variable is in the exact right order. Its a mess and probably very inefficient, so it'd be best to start over from scratch with the help of people that know PHP way better than I do.
As others said use an array, but I would do it this way
//settings1.default.php
<?php
return [
'apikey' => "11111111111111",
'TZ' => "Europe/London";
'UTC' => "1";
'lon' => 0.2;
'lat' => 50.1;
];
Then when you load them you can do it this way:
$default = require 'settings1.default.php';
$settings = require 'settings1.php';
//you could also use array_replace_recursive() but I would avoid array_merge_recursive()
$settings = array_merge($default, $settings);
And then if you want you can just use the merged arrays or, you can save that to a file like this:
file_put_contents('settings1.php', '<?php return '.var_export($settings, true).';');
Var Export returns a syntactically correct array, and the second argument returns it as a string rather then outputting it. Then you just need to add the <?php tag, the return and the closing ; to have PHP file.
This also keeps your variable space clean, if you add a variable, you have no grantee that someone using this does not already have that variable in use. If they don't follow best practices in there code, there is the potential to overwrite data from one or both with unknown consequences. It would also be a bit hard to debug an issue like that.
Your way
It's possible to do what you want without doing this, but you will have to include the files in a function (so you have a clean scope), call get_defined_vars then merge the 2 arrays, then loop over that and manually create the PHP for the file.
If you don't use get_defined_vars in a "clean" scope you risk importing other variables into your settings files. This could lead to security issues as well. What I mean by clean scope (just to be clear) is that within an empty function, the only variables that are defined are the ones used as arguments of the function (something we should all agree on). So by doing this we can easily remove the only "non-setting" variable, which is the filename. This way we can avoid a lot of those issues. Without doing that you really have no way to know what all would be included in get_defined_vars();, or at least I don't have any idea what could leak into it.
function loadSettings($file){
require $file;
unset($file); //remove file var you cant use this variable name in either file
return get_defined_vars();
}
$default = loadSettings('settings1.default.php');
$settings = loadSettings('settings1.php');
//you could also use array_replace_recursive() but I would avoid array_merge_recursive()
$settings = array_merge($default, $settings);
$code = '<?php'."\n";
foreach($settings AS $var => $value){
/// ${var} = "{value}";\n
$code .= '$'.$var.' = "'.$value.'"'.";\n"; //some issues with quotes on strings .. and typing here (no objects etc)
}
file_put_contents('settings1.php', $code);
Which just seems like a mess to me. Please note that you will have issues with the quotes on strings etc.. For example in the above code if the value of $value is 'some "string" here', this would create this line in the file $foo = "some "string" here"; which is a syntax error. Var Export automatically escapes these things for you. Not to mention what happens if you try to put an array in that value... Etc. Frankly I am to lazy to try to work out all the edge cases for that. Its what I like to call a naive implementation, because at first it looks easy but as you really get into it you have all these edge cases pop up.
Probably the only way to really fix that is to use var_export on each line like this:
//...
foreach($settings AS $var => $value){
/// ${var} = "{value}";\n
$code .= '$'.$var.' = '.var_export($value,true).";\n";
}
//...
You could try to do things like check if its an array, escape any non-escaped " some more type checking etc. But whats the point as you may find other edge cases later etc.. Just a headache. Var Export does a fantastic job of escaping the, and if you compare the two versions of the code, it should be clear why I made the original suggestion first.
One last note, is you can probably simplify the mixed quotes ' and ". I am just in a habit of doing everything that is PHP code in ' because you can get into problems with this stuff.
//don't do this
$code .= "$$var = ".var_export($value,true).";\n";
//or this
$code .= "${$var} = ".var_export($value,true).";\n";
As PHP will think that is code and not a string. Well it will see it as a variable variable, not something you want.
UPDATE
Based on your comment
Ended up using the second method you came up with. Also, figured out that if i replaced require with include inside the function, it would return an empty array, so the settings1.php file gets created with default values if it doesn't exist. Only thing I still need to work out is the easiest way to require settings1.default.php but not require settings1.php
I would make this small change:
function loadSettings($file){
if(!file_exists($file)) return []; //add this line
require $file;
unset($file); //remove file var you cant use this variable name in either file
return get_defined_vars();
}
While include has the behaviour you want, its not really the right thing to use here as you mentioned
I still need to work out is the easiest way to require settings1.default.php but not require settings1.php
This breaks the commonality between them, which means we have to write more code with little or no benefit. We can avoid that by adding a check in. The only difference here is it makes using require vs include a bit pointless, and both files would return an empty array if they don't exist. I would still use require because it means this code is important when you glance at it, rather or not it really does anything.
The part in bold above we can actually fix very easily by doing this:
function loadSettings($file){
if(basename($file) != 'settings1.default.php' && !file_exists($file)) return []; //add this line
require $file;
unset($file); //remove file var you cant use this variable name in either file
return get_defined_vars();
}
I left checking for the files orignally because I thought both file would always exist, and be required. Adding the filename in there also adds a hard dependency on the setting file name. If that file name changed you would have to change the code. So i wanted to add it separate, as the other behaviour may be fine.
Base name gets the trailing part of the path to avoid issues with full paths to the file, this will return the filename. Which makes matching it to our string of the filename a bit easier as we don't have to worry about the path.
So if the basename of the file is not equal to our settings.default file and the file does not exist return an array. Then when the file is equal to that file it will bail out of the if condition and go to the require part rather or not the settings.default file exits. Basically this will treat settings.default as a require, but still return an array on other files if they don't exist (like an include ).
Cheers!
I would just store all of the variables in an array, then use extract to convert them to the actual variables, and use array_intersect_key to see if they length of the intersection of the arrays is the same as the length of $defaultSettings:
//settings1.default.php
$defaultSettings = [
'apikey' => "11111111111111",
'TZ' => "Europe/London";
'UTC' => "1";
'lon' => 0.2;
'lat' => 50.1;
];
//settings.php
$settings = [
'apikey' => "11111111111111",
'TZ' => "Europe/London";
'UTC' => "1";
'lon' => 0.2;
'lat' => 50.1;
];
extract($settings); // creates the variables $apikey, $TZ, etc.
//check.php
require('settings1.default.php')
require('settings.php')
//if they don't have the same keys
if (count(array_intersect_key($settings , $defaultSettings)) !== count($defaultSettings)) {
throw new \Exception("Invalid configuration");
}
You have to include settings1.default.php in settings1.php and then have to call get_defined_vars() which will have list of vars defined in settings1.default.php then if some variable does not exist in that array build additional config values in settings1.php.
settings1.php.
<?php
include_once('settings1.default.php');
$varialbes_defined_settings1_default = get_defined_vars();
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's an actual use of variable variables?
i saw the concept of variable variables in php .
that is a variable whose name is contained in another variable .
like this
$name = ’foo’;
$$name = ’bar’;
echo $foo;
// Displays ’bar’
one advantage that i see is , you can create variable names with numbers or lettes which you can not use normally . like this
$name = ’123’;
/* 123 is your variable name, this would normally be invalid. */
$$name = ’456’;
// Again, you assign a value
echo ${’123’};
// Finally, using curly braces you can output ’456’
and also you can call some functions like this
function myFunc() {
echo ’myFunc!’;
}
$f = ’myFunc’;
$f(); // will call myFunc();
and in a book i saw this
Variable variables are a very powerful tool, and should be used with
extreme care, not only because they can make your code difficult to
understand and document, but also because their improper use can lead
to some significant security issues.
The problem i have is if using variable variables in the code can be that dangerous . why are we using it . and is there any major advantages using variable variables in my code , if any what are those advantages .
you can use it in case of not-user-input. Look
function getVar($gid){
$name = "gid".$gid;
global $$name;
$var = $$name;
return $var;
}
It's useful when you have a lot of variables (same start with ending number, etc...) which is probably save
Look at your example:
function myFunc() {
echo ’myFunc!’;
}
$f = ’myFunc’;
$f(); // will call myFunc();
It is powerful: $f can have a value dynamically and the function called based on this value.
At the same time: If the user was given limitless access to $f this could be a security threat
In some MVC Frameworks they use it to run a function which will vary depending on the URL:
http://www.domain.com/thecontroller/theaction
in PHP side they will parse the url, get the second segment which is the name of the function then run it, but how? they will assign to a variable like what you have mentioned:
$toRun = 'theaction';
$toRun();
I've used double and even treble indirect pointers in C, but have never explicitly used variable variables in PHP (but I have used variable functions and classes).
I think it's somehow reassuring that there's more functionality in PHP than I use - and that I can make informed choices about which constructs I do use (I often use explicit references for example).
A nice usage I saw in some framework is using them to access, easier, values passedfrom another script as an array:
$array['test'];
$array['other'];
$array['third_index'];
// or simply $array = array('test','other','third_index');
foreach($array as $k=>$v)
{
$$k = $v;
}
So you could then have $test, $other and $third_index being usable as variables. Pretty handy when dealing with views, for example.
I know that directly setting a variable in the scope of caller is probably not a good idea.
However, the PHP extract() function does exactly that! I would like to write my own version of extract() but cannot figure out how to actually go about setting the variables in the caller. Any ideas?
The closest I have come is modifying the caller's args using debug_backtrace(), but this is not exactly the same thing...
You can't modify local variables in a parent scope - the method which extract() uses is not exposed by PHP.
Also, what you get back from debug_stacktrace() isn't magically linked to the real stack. You can't modify it and hope your modifications are live!
You could only do it in a PHP extension. If you call an internal PHP function, it will not run in a new PHP scope (i.e., no new symbol table will be created). Therefore, you can modify the "parent scope" by changing the global EG(active_symbol_table).
Basically, the core of the function would do something like extract does, the core of which is:
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
//loop through the given array
ZEND_SET_SYMBOL_WITH_LENGTH(EG(active_symbol_table),
Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, data, 1, 0);
There are, however, a few nuances. See the implementation of extract, but keep in mind a function that did what you wanted wouldn't need to be as complex; most of the code in extract is there to deal with the several options it accepts.
You can abuse the $GLOBALS scope to read and write variables from the caller of your function. See below sample function, which reads and write variables from the caller scope.
And yes, I know its dirty to abuse the $GLOBAL scope, but hey, we're here to fix problems ain't we? :)
function set_first_name($firstname) {
/* check if $firstname is defined in caller */
if(array_key_exists('firstname', $GLOBALS)) {
$firstname_was = $GLOBALS['firstname'];
} else {
$firstname_was = 'undefined';
}
/* set $firstname in caller */
$GLOBALS['firstname'] = $firstname;
/* show onscreen confirmation for debugging */
echo '<br>firstname was ' . $firstname_was . ' and now is: ' . $firstname;
}
set_first_name('John');
set_first_name('Michael');
The function returns the following output:
<br>firstname was undefined and now is: John
<br>firstname was John and now is: Michael
It depends on how badly you need to do this. If it's only for source beauty, find another way. If, for some reason, you really need to mess with parent scope, there's always a way.
SOLUTION 1
The safest method would be to actually use extract itself for this job, since it knows the trick. Say you want to make a function that extracts elements of an array but with all the names backwards - pretty weird! -, let's do this with a simple array-to-array transformation:
function backwardNames($x) {
$out = [];
foreach($x as $key=>$val) {
$rev = strrev($key);
$out[$rev] = $val;
}
return $out;
}
extract(backwardNames($myArray));
No magic here.
SOLUTION 2
If you need more than what extract does, use eval and var_export. YES I KNOW I KNOW everybody calm down please. No, eval is not evil. Eval is a power tool and it can be dangerous if you use it without care - so use it with care. (There is no way to go wrong if you only eval something that's been generated by var_export - it doesn't give any way to intrusions even if you put values in your array from an untrusted source. Array elements behave well.)
function makeMyVariables() {
$vars = [
"a" => 4,
"b" => 5,
];
$out = var_export($vars,1);
$out = "extract(".$out.");";
return $out;
}
eval(makeMyVariables()); // this is how you call it
// now $a is 4, $b is 5
This is almost the same, except that you can do a lot more in eval. And it's significantly slower, of course.
However, indeed, there is no way to do it with a single call.
I'm developing a PHP application and I'm wondering about the best way to include multi-language support for users in other countries.
I'm proficient with PHP but have never developed anything with support for other languages.
I was thinking of putting the language into a PHP file with constants, example:
en.php could contain:
define('HZ_DB_CONN_ERR', 'There was an error connecting to the database.');
and fr.php could contain:
define('HZ_DB_CONN_ERR', 'whatever the french is for the above...');
I could then call a function and automatically have the correct language passed in.
hz_die('HZ_DB_CONN_ERR', $this);
Is this a good way of going about it?
-- morristhebear.
Weird. People seem to be ignoring the obvious solution. Your idea of locale-specific files is fine. Have en.php:
define('LOGIN_INCORRECT','Your login details are incorrect.');
...
Then, assuming you have a global config/constants file (which I'd suggest for many reasons), have code like this:
if ($language == 'en') {
reqire_once 'en.php';
} else if ($language == 'de') {
require_once 'de.php';
}
You can define functions for number and currency display, comparison/sorting (ie German, French and English all have different collation methods), etc.
People often forget PHP is a dynamic language so things like this:
if ($language == 'en') {
function cmp($a, $b) { ... }
} else if ($language == 'de') {
function cmp($a, $b) { ... }
}
are in fact perfectly legal. Use them.
You can use gettext or something which supports gettext as well as more such as Zend_Translate.
Edit:
Just for precision, Zend_Translate supports gettext without the gettext module. You can see here the many different types of input it supports.
If you use arrays as also suggested you can also use this with Zend_Translate. The point being, if you use arrays today and gettext, xml or something else tomorrow you only have to change your config for Zend_Translate.
I really love the following approach:
one file is the translator itself:
class Translator{
private static $strs = array();
private static $currlang = 'en';
public static function loadTranslation($lang, $strs){
if (empty(self::$strs[$lang]))
self::$strs[$lang] = array();
self::$strs[$lang] = array_merge(self::$strs[$lang], $strs);
}
public static function setDefaultLang($lang){
self::$currlang = $lang;
}
public static function translate($key, $lang=""){
if ($lang == "") $lang = self::$currlang;
$str = self::$strs[$lang][$key];
if (empty($str)){
$str = "$lang.$key";
}
return $str;
}
public static function freeUnused(){
foreach(self::$strs as $lang => $data){
if ($lang != self::$currlang){
$lstr = self::$strs[$lang]['langname'];
self::$strs[$lang] = array();
self::$strs[$lang]['langname'] = $lstr;
}
}
}
public static function getLangList(){
$list = array();
foreach(self::$strs as $lang => $data){
$h['name'] = $lang;
$h['desc'] = self::$strs[$lang]['langname'];
$h['current'] = $lang == self::$currlang;
$list[] = $h;
}
return $list;
}
public static function &getAllStrings($lang){
return self::$strs[$lang];
}
}
function generateTemplateStrings($arr){
$trans = array();
foreach($arr as $totrans){
$trans[$totrans] = Translator::translate($totrans);
}
return $trans;
}
the language-files can be simply include()d and look like this:
en.php:
Translator::loadTranslation('en', array(
'textfield_1' => 'This is some Textfield',
'another_textfield ' => 'This is a longer Text showing how this is used',
));
de.php:
Translator::loadTranslation('de', array(
'textfield_1' => 'Dies ist ein Textfeld',
'another_textfield ' => 'Dies ist ein längerer Text, welcher aufzeigt, wie das hier funktioniert.',
));
in you app you can do either translate one string like this:
$string = Translator::translate('textfield_1')
or even a bunch of strings:
$strings = generateTemplateStrings(array('textfield_1', 'another_textfield'));
Because the language-files can just be included, you can stack the very easily and, say, include a global file first and then include files from submodules which can either add new strings or replace already defined ones (which doesn't work with the define()-method).
Because it's pure PHP, it can even be opcode-cached very easily.
I even have scripts around which generate CSV-files containing untranslated strings from a file and even better: convert the translated CSV-file back to the language file.
I have this solution in productive use since 2004 and I'm so very happy with this.
Of course, you can even extend it with conventions for pluralizing for example. Localizing number formats is something you'd have to do using other means though - the intl-extension comes to mind.
Thanks to all the people for your approaches and solutions. I came here with the same beggining doubt, and i can conlude, that to use the "define method" is more realistic, as, even with the odd problem that doesn't use very stylish methods with other libraries or some, being realistic and in a productive thinking, is so easy to mantain, and understand, so, you can get other languages trough non programing skills dudes.
I consider better that the arrays method, as you don't need to distribute that big multilanguage to get some traductions, besides, you are using less memory as you are loading only the needed traducted strings.
About the thing that, those can't be redefined; well, generrally if you are defining constants is because they don't need or must not be changed, so if needed that you can use a section for defined strings and variable ones.
I addmint that i don't like the way those define files looks but, take in count that your visitors are not worried at all about the way idiom is implemented, is a perfect valid implementations and you'll can easily get some traductions.
You might want to look at a framework like CakePHP or CodeIgniter that make writing internationalized applications much easier. It's not just strings you have to consider -- things like number formats and date formats also have to be accounted for
Your solution should work fine as long as it is solely intended for translating. As others have mentioned, there are many other locale-based variables, such as currency and date formats.
A solid approach to making your application locale-proof would be to use Zend_Locale combined with Zend_Translate.
Zend_Locale allows you to easily detect the user's locale, or set it if you wish. This class is useful for automatically setting the correct currency format, for example.
Zend_Translate allows you to easily translate text using several different formats:
Array
CSV
Gettext
Ini
Tbx
Tmx
Qt
Xliff
XmlTm
Your approach is workable, in the case where you include different constantfiles depending on which language the user has choosen.
You could also skip the constant-part and just define a big hashtable with constant => translation to prevent crashes in namespace.
file: en.php
$constants = Array(
'CONSTANT_KEY' => 'Translated string'
);
file: functions.php
function getConstant($key, $fallback) {
// ... return constant or fallback here.
}
However, when it comes to large amount of data, this approach will be hard to maintain. There are a few other approaches that might serve your purpose better, for instance, an ideal solution is where all your constants are stored in a global memoryspace for your entire site, to avoid having each and every reguest/thread keeping all this translated data in memory. This requires some sort php module-approach. Gettext as someone here suggested might use that approach.
Google for PHP localization to find useful resources.
One tip for you, is to create a function that returns the translated string, and if it is not in the hashtable, then return the hash key you requested with something like a * behind it to notify you it needs translation.
Here is how I do it:
parent_script.php:
$lang_pick = "EN"; //use your own method to set language choice
require_once('trans_index.php');
echo $txt['hello'];
trans_index.php :
$text = array();
$text['hello'] = array (
"EN"=> "Hello",
"FR"=> "Bonjour",
"DE"=> "Guten Tag",
"IT"=> "Ciao"
); //as many as needed
foreach($text as $key => $val) {
$txt[$key] = $text[$key][$lang_pick];
}
That may be too simple for your needs, but I find it very workable. It also makes it very easy to maintain the multiple versions of the text.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I know this sounds like a point-whoring question but let me explain where I'm coming from.
Out of college I got a job at a PHP shop. I worked there for a year and a half and thought that I had learned all there was to learn about programming.
Then I got a job as a one-man internal development shop at a sizable corporation where all the work was in C#. In my commitment to the position I started reading a ton of blogs and books and quickly realized how wrong I was to think I knew everything. I learned about unit testing, dependency injection and decorator patterns, the design principle of loose coupling, the composition over inheritance debate, and so on and on and on - I am still very much absorbing it all. Needless to say my programming style has changed entirely in the last year.
Now I find myself picking up a php project doing some coding for a friend's start-up and I feel completely constrained as opposed to programming in C#. It really bothers me that all variables at a class scope have to be referred to by appending '$this->' . It annoys me that none of the IDEs that I've tried have very good intellisense and that my SimpleTest unit tests methods have to start with the word 'test'. It drives me crazy that dynamic typing keeps me from specifying implicitly which parameter type a method expects, and that you have to write a switch statement to do method overloads. I can't stand that you can't have nested namespaces and have to use the :: operator to call the base class's constructor.
Now I have no intention of starting a PHP vs C# debate, rather what I mean to say is that I'm sure there are some PHP features that I either don't know about or know about yet fail to use properly. I am set in my C# universe and having trouble seeing outside the glass bowl.
So I'm asking, what are your favorite features of PHP? What are things you can do in it that you can't or are more difficult in the .Net languages?
Documentation. The documentation gets my vote. I haven't encountered a more thorough online documentation for a programming language - everything else I have to piece together from various websites and man pages.
Arrays. Judging from the answers to this question I don't think people fully appreciate just how easy and useful Arrays in PHP are. PHP Arrays act as lists, maps, stacks and generic data structures all at the same time. Arrays are implemented in the language core and are used all over the place which results in good CPU cache locality. Perl and Python both use separate language constructs for lists and maps resulting in more copying and potentially confusing transformations.
Stream Handlers allow you to extend the "FileSystem" with logic that as far as I know is quite difficult to do in most other languages.
For example with the MS-Excel Stream handler you can create a MS Excel file in the following way:
$fp = fopen("xlsfile://tmp/test.xls", "wb");
if (!is_resource($fp)) {
die("Cannot open excel file");
}
$data= array(
array("Name" => "Bob Loblaw", "Age" => 50),
array("Name" => "Popo Jijo", "Age" => 75),
array("Name" => "Tiny Tim", "Age" => 90)
);
fwrite($fp, serialize($data));
fclose($fp);
Magic Methods are fall-through methods that get called whenever you invoke a method that doesn't exist or assign or read a property that doesn't exist, among other things.
interface AllMagicMethods {
// accessing undefined or invisible (e.g. private) properties
public function __get($fieldName);
public function __set($fieldName, $value);
public function __isset($fieldName);
public function __unset($fieldName);
// calling undefined or invisible (e.g. private) methods
public function __call($funcName, $args);
public static function __callStatic($funcName, $args); // as of PHP 5.3
// on serialize() / unserialize()
public function __sleep();
public function __wakeup();
// conversion to string (e.g. with (string) $obj, echo $obj, strlen($obj), ...)
public function __toString();
// calling the object like a function (e.g. $obj($arg, $arg2))
public function __invoke($arguments, $...);
// called on var_export()
public static function __set_state($array);
}
A C++ developer here might notice, that PHP allows overloading some operators, e.g. () or (string). Actually PHP allows overloading even more, for example the [] operator (ArrayAccess), the foreach language construct (Iterator and IteratorAggregate) and the count function (Countable).
The standard class is a neat container. I only learned about it recently.
Instead of using an array to hold serveral attributes
$person = array();
$person['name'] = 'bob';
$person['age'] = 5;
You can use a standard class
$person = new stdClass();
$person->name = 'bob';
$person->age = 5;
This is particularly helpful when accessing these variables in a string
$string = $person['name'] . ' is ' . $person['age'] . ' years old.';
// vs
$string = "$person->name is $person->age years old.";
Include files can have a return value you can assign to a variable.
// config.php
return array(
'db' => array(
'host' => 'example.org',
'user' => 'usr',
// ...
),
// ...
);
// index.php
$config = include 'config.php';
echo $config['db']['host']; // example.org
You can take advantage of the fact that the or operator has lower precedence than = to do this:
$page = (int) #$_GET['page']
or $page = 1;
If the value of the first assignment evaluates to true, the second assignment is ignored. Another example:
$record = get_record($id)
or throw new Exception("...");
__autoload() (class-) files aided by set_include_path().
In PHP5 it is now unnecessary to specify long lists of "include_once" statements when doing decent OOP.
Just define a small set of directory in which class-library files are sanely structured, and set the auto include path:
set_include_path(get_include_path() . PATH_SEPARATOR . '../libs/');`
Now the __autoload() routine:
function __autoload($classname) {
// every class is stored in a file "libs/classname.class.php"
// note: temporary alter error_reporting to prevent WARNINGS
// Do not suppress errors with a # - syntax errors will fail silently!
include_once($classname . '.class.php');
}
Now PHP will automagically include the needed files on-demand, conserving parsing time and memory.
Easiness. The greatest feature is how easy it is for new developers to sit down and write "working" scripts and understand the code.
The worst feature is how easy it is for new developers to sit down and write "working" scripts and think they understand the code.
The openness of the community surrounding PHP and the massive amounts of PHP projects available as open-source is a lot less intimidating for someone entering the development world and like you, can be a stepping stone into more mature languages.
I won't debate the technical things as many before me have but if you look at PHP as a community rather than a web language, a community that clearly embraced you when you started developing, the benefits really speak for themselves.
Variable variables and functions without a doubt!
$foo = 'bar';
$bar = 'foobar';
echo $$foo; //This outputs foobar
function bar() {
echo 'Hello world!';
}
function foobar() {
echo 'What a wonderful world!';
}
$foo(); //This outputs Hello world!
$$foo(); //This outputs What a wonderful world!
The same concept applies to object parameters ($some_object->$some_variable);
Very, very nice. Make's coding with loops and patterns very easy, and it's faster and more under control than eval (Thanx #Ross & #Joshi Spawnbrood!).t
You can use functions with a undefined number of arguments using the func_get_args().
<?php
function test() {
$args = func_get_args();
echo $args[2]; // will print 'd'
echo $args[1]; // will print 3
}
test(1,3,'d',4);
?>
I love remote files. For web development, this kind of feature is exceptionally useful.
Need to work with the contents of a web page? A simple
$fp = fopen('http://example.com');
and you've got a file handle ready to go, just like any other normal file.
Or how about reading a remote file or web page directly in to a string?
$str = file_get_contents('http://example.com/file');
The usefulness of this particular method is hard to overstate.
Want to analyze a remote image? How about doing it via FTP?
$imageInfo = getimagesize('ftp://user:password#ftp.example.com/image/name.jpg');
Almost any PHP function that works with files can work with a remote file. You can even include() or require() code files remotely this way.
strtr()
It's extremely fast, so much that you would be amazed. Internally it probably uses some crazy b-tree type structure to arrange your matches by their common prefixes. I use it with over 200 find and replace strings and it still goes through 1MB in less than 100ms. For all but trivially small strings strtr() is even significantly faster than strtolower() at doing the exact same thing, even taking character set into account. You could probably write an entire parser using successive strtr calls and it'd be faster than the usual regular expression match, figure out token type, output this or that, next regular expression kind of thing.
I was writing a text normaliser for splitting text into words, lowercasing, removing punctuation etc and strtr was my Swiss army knife, it beat the pants off regular expressions or even str_replace().
One not so well known feature of PHP is extract(), a function that unpacks an associative array into the local namespace. This probably exists for the autoglobal abormination but is very useful for templating:
function render_template($template_name, $context, $as_string=false)
{
extract($context);
if ($as_string)
ob_start();
include TEMPLATE_DIR . '/' . $template_name;
if ($as_string)
return ob_get_clean();
}
Now you can use render_template('index.html', array('foo' => 'bar')) and only $foo with the value "bar" appears in the template.
Range() isn't hidden per se, but I still see a lot of people iterating with:
for ($i=0; $i < $x; $i++) {
// code...
}
when they could be using:
foreach (range(0, 12) as $number) {
// ...
}
And you can do simple things like
foreach (range(date("Y"), date("Y")+20) as $i)
{
print "\t<option value=\"{$i}\">{$i}</option>\n";
}
PHP enabled webspace is usually less expensive than something with (asp).net.
You might call that a feature ;-)
The static keyword is useful outside of a OOP standpoint. You can quickly and easily implement 'memoization' or function caching with something as simple as:
<?php
function foo($arg1)
{
static $cache;
if( !isset($cache[md5($arg1)]) )
{
// Do the work here
$cache[md5($arg1)] = $results;
}
return $cache[md5($arg1)];
}
?>
The static keyword creates a variable that persists only within the scope of that function past the execution. This technique is great for functions that hit the database like get_all_books_by_id(...) or get_all_categories(...) that you would call more than once during a page load.
Caveat: Make sure you find out the best way to make a key for your hash, in just about every circumstance the md5(...) above is NOT a good decision (speed and output length issues), I used it for illustrative purposes. sprintf('%u', crc32(...)) or spl_object_hash(...) may be much better depending on the context.
One nice feature of PHP is the CLI. It's not so "promoted" in the documentation but if you need routine scripts / console apps, using cron + php cli is really fast to develop!
Then "and print" trick
<?php $flag and print "Blah" ?>
Will echo Blah if $flag is true. DOES NOT WORK WITH ECHO.
This is very handy in template and replace the ? : that are not really easy to read.
You can use minus character in variable names like this:
class style
{
....
function set_bg_colour($c)
{
$this->{'background-color'} = $c;
}
}
Why use it? No idea: maybe for a CSS model? Or some weird JSON you need to output. It's an odd feature :)
HEREDOC syntax is my favourite hidden feature. Always difficult to find as you can't Google for <<< but it stops you having to escape large chunks of HTML and still allows you to drop variables into the stream.
echo <<<EOM
<div id="someblock">
<img src="{$file}" />
</div>
EOM;
Probably not many know that it is possible to specify constant "variables" as default values for function parameters:
function myFunc($param1, $param2 = MY_CONST)
{
//code...
}
Strings can be used as if they were arrays:
$str = 'hell o World';
echo $str; //outputs: "hell o World"
$str[0] = 'H';
echo $str; //outputs: "Hell o World"
$str[4] = null;
echo $str; //outputs: "Hello World"
The single most useful thing about PHP code is that if I don't quite understand a function I see I can look it up by using a browser and typing:
http://php.net/function
Last month I saw the "range" function in some code. It's one of the hundreds of functions I'd managed to never use but turn out to be really useful:
http://php.net/range
That url is an alias for http://us2.php.net/manual/en/function.range.php. That simple idea, of mapping functions and keywords to urls, is awesome.
I wish other languages, frameworks, databases, operating systems has as simple a mechanism for looking up documentation.
Fast block comments
/*
die('You shall not pass!');
//*/
//*
die('You shall not pass!');
//*/
These comments allow you to toggle if a code block is commented with one character.
My list.. most of them fall more under the "hidden features" than the "favorite features" (I hope!), and not all are useful, but .. yeah.
// swap values. any number of vars works, obviously
list($a, $b) = array($b, $a);
// nested list() calls "fill" variables from multidim arrays:
$arr = array(
array('aaaa', 'bbb'),
array('cc', 'd')
);
list(list($a, $b), list($c, $d)) = $arr;
echo "$a $b $c $d"; // -> aaaa bbb cc d
// list() values to arrays
while (list($arr1[], $arr2[], $arr3[]) = mysql_fetch_row($res)) { .. }
// or get columns from a matrix
foreach($data as $row) list($col_1[], $col_2[], $col_3[]) = $row;
// abusing the ternary operator to set other variables as a side effect:
$foo = $condition ? 'Yes' . (($bar = 'right') && false) : 'No' . (($bar = 'left') && false);
// boolean False cast to string for concatenation becomes an empty string ''.
// you can also use list() but that's so boring ;-)
list($foo, $bar) = $condition ? array('Yes', 'right') : array('No', 'left');
You can nest ternary operators too, comes in handy sometimes.
// the strings' "Complex syntax" allows for *weird* stuff.
// given $i = 3, if $custom is true, set $foo to $P['size3'], else to $C['size3']:
$foo = ${$custom?'P':'C'}['size'.$i];
$foo = $custom?$P['size'.$i]:$C['size'.$i]; // does the same, but it's too long ;-)
// similarly, splitting an array $all_rows into two arrays $data0 and $data1 based
// on some field 'active' in the sub-arrays:
foreach ($all_rows as $row) ${'data'.($row['active']?1:0)}[] = $row;
// slight adaption from another answer here, I had to try out what else you could
// abuse as variable names.. turns out, way too much...
$string = 'f.> <!-? o+';
${$string} = 'asdfasf';
echo ${$string}; // -> 'asdfasf'
echo $GLOBALS['f.> <!-? o+']; // -> 'asdfasf'
// (don't do this. srsly.)
${''} = 456;
echo ${''}; // -> 456
echo $GLOBALS['']; // -> 456
// I have no idea.
Right, I'll stop for now :-)
Hmm, it's been a while..
// just discovered you can comment the hell out of php:
$q/* snarf */=/* quux */$_GET/* foo */[/* bar */'q'/* bazz */]/* yadda */;
So, just discovered you can pass any string as a method name IF you enclose it with curly brackets. You can't define any string as a method alas, but you can catch them with __call(), and process them further as needed. Hmmm....
class foo {
function __call($func, $args) {
eval ($func);
}
}
$x = new foo;
$x->{'foreach(range(1, 10) as $i) {echo $i."\n";}'}();
Found this little gem in Reddit comments:
$foo = 'abcde';
$strlen = 'strlen';
echo "$foo is {$strlen($foo)} characters long."; // "abcde is 5 characters long."
You can't call functions inside {} directly like this, but you can use variables-holding-the-function-name and call those! (*and* you can use variable variables on it, too)
Array manipulation.
Tons of tools for working with and manipulating arrays. It may not be unique to PHP, but I've never worked with a language that made it so easy.
I'm a bit like you, I've coded PHP for over 8 years. I had to take a .NET/C# course about a year ago and I really enjoyed the C# language (hated ASP.NET) but it made me a better PHP developer.
PHP as a language is pretty poor, but, I'm extremely quick with it and the LAMP stack is awesome. The end product far outweighs the sum of the parts.
That said, in answer to your question:
http://uk.php.net/SPL
I love the SPL, the collection class in C# was something that I liked as soon as I started with it. Now I can have my cake and eat it.
Andrew
I'm a little surprised no-one has mentioned it yet, but one of my favourite tricks with arrays is using the plus operator. It is a little bit like array_merge() but a little simpler. I've found it's usually what I want. In effect, it takes all the entries in the RHS and makes them appear in a copy of the LHS, overwriting as necessary (i.e. it's non-commutative). Very useful for starting with a "default" array and adding some real values all in one hit, whilst leaving default values in place for values not provided.
Code sample requested:
// Set the normal defaults.
$control_defaults = array( 'type' => 'text', 'size' => 30 );
// ... many lines later ...
$control_5 = $control_defaults + array( 'name' => 'surname', 'size' => 40 );
// This is the same as:
// $control_5 = array( 'type' => 'text', 'name' => 'surname', 'size' => 40 );
Here's one, I like how setting default values on function parameters that aren't supplied is much easier:
function MyMethod($VarICareAbout, $VarIDontCareAbout = 'yippie') { }
Quick and dirty is the default.
The language is filled with useful shortcuts, This makes PHP the perfect candidate for (small) projects that have a short time-to-market.
Not that clean PHP code is impossible, it just takes some extra effort and experience.
But I love PHP because it lets me express what I want without typing an essay.
PHP:
if (preg_match("/cat/","one cat")) {
// do something
}
JAVA:
import java.util.regex.*;
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat")
if (m.find()) {
// do something
}
And yes, that includes not typing Int.