Friday, December 12

Do you Know this About PHP ?

. Test Boolean Results with Switch. We all know that we can use switch to test cases, like this:

<?php

switch ($a) {

case 'a':
echo 'Yay it is A';
break;

case 'b':

echo 'Yahoo! Its B!';
break;
}
But did you know that you can test for Boolean values with a switch?
The trick is to use it as follows:
<?php

switch (TRUE) {

case ($a == 'A'):
echo 'Yay it is A';
break;

case ($a == 'B'):

echo 'Yahoo! Its B!';
break;
}
The principle might not hit you until you think about it, but once it does it's quite clear that switch can actually make things very simple for you if you use it in this way as well.



2. Variable Variables.

This is my favorite accidental find in programming. What it comes down to is that a variable can have a variable name. Where would you use something like this? Well, image we have a class name that is dependent on the url in some way. For the sake of simplicity I am going to fore-go filtering and validation and simply say
<?php
$class_name = $_GET['class_name'];

Now, let's assume that once we have the class name, we need to instantiate the class and the object name also needs to be the same as the class name. Thus we can say

$$class_name = new $class_name();
And therefore, if the value of $class_name is 'water', we will have an object named $water. See the power here?
Many developers consider it a hack. But with the right filtering and careful validation, in other words if you code it properly, it can work very well. PHP was built to be able to do this and you can apply it to function names, arrays, variables or objects.





3.Extract is your friend. Ever been in the situation where you need to say something like:


<?php
$name = $array['name'];
$surname = $array['surname'];
$message = $array['message'];

Then you may want to recall that you can use extract() to do the same.
Put simply, extract will remove the work behind this.
In this case, saying:

<?php
extract($array);

Will automatically make $name = $array['name'];
So, you can say "hello ".$name." ".$surname." Without do all of the declarations.
Of course, you always need to be mindful of validation and filtering, but there is a right way and a wrong way to do anything with PHP.

No comments:

Post a Comment