I have been developing applications in PHP for years, but recently I came across upon functions and features that I did not know about. Some of these can be quite useful and help a PHP developer during their projects . With that in mind, I’ve compiled a list of five extremely useful PHP functions that a PHP developer should be familiar with.
1) Arbitrary Arguments
You might have heard the word ‘Arbitrary Arguments’ for the first time. In php or other development you create many functions with fixed arguments and at the time of calling function you pass same number of arguments or less then that. But now you can pass as many arguments as you want using func_get_args().the parameters are not limited. For this function arguments are empty.
Check following example:
function test() { $args = func_get_args(); foreach ($args as $k => $v) { echo "arg".($k+1).": $v\n"; } } test(); Output: /* prints nothing */ test('hello'); Output: arg1: hello test('hi','goodmorning','john'); Output: arg1: hi arg2: goodmorning arg3: john
2) Using Glob() to Find Files
In php you find many different functions to find file from directory. Limitation of those functions are it’s display all files from folder.
Glob() function is different from all other functions, you can find files with different patterns like following.
$files = glob('*.js'); print_r($files); output: Array ( [0] => jquery.js [1] => datepicker.js [2] => bootstrep.js [3] => custom.js ) $files = glob('*.{js,css}', GLOB_BRACE); print_r($files); output: Array ( [0] => jquery.js [1] => datepicker.js [2] => bootstrep.js [3] => custom.js [4] => custom.css [5] => style.css ) $files = glob('c*.js'); print_r($files); output: Array ( [0] => calender.js [1] => custom.js )
3) Predefined Magic Constants
In code, many time you find some text between double underscore. You have defined too many custom constant in script. PHP provides number of predefined constants. Many of those are created by different extensions. If respective extension is available then only you can used that extensions constantly.
Following are some common predefined constants:
__CLASS__ __DIR__ __FILE__ __FUNCTION__ __LINE__ __METHOD__ __NAMESPACE__ __TRAIT__
Example for __FILE__
// this is relative to the loaded script’s path it may cause problems when running scripts from different directories rquire_once(‘config/database.php’);
// this is always relative to this file’s path no matter where it was included from
rquire_once(dirname(__FILE__) . ‘/config/database.php’);