DevtheWeb.NET

for Those Who Develop Something on the Web

Things You Probably Didn’t Know About PHP – Part 2

Date: 19 Jan 2010 Comments: 11 so far

Here a new post about cool things in PHP that I found in my spare time. Here’s the list:

1. Use === and !== when you want to compare only variables with identical format, ex:

$a = 1;
$b = ‘1’;
$c = 1;

$a == $b // true
$a === $b // false
$a === $c // true

2. You can return multiple values from a function with “by reference” parameters, ex:

function func(&$var1, &$var2)
{
$var1++;
$var2–;
}

$a = 5;
$b = 5;

func($a, $b);

// $a is 6, $b is 4

3. You can handle the result when try to echo a class instance – just define a custom  __toString() in your class:

class SimpleClass {
protected $title;

public function __construct($str) {
$this->title = $str;
}

class BetterClass {
protected $title;

public function __construct($str) {
$this->title = $str;
}

public function __toString() {
return $this->title;
}
}

$a = new SimpleClass(‘Simple Class (a)’);

$b = new BetterClass(‘Better Class (b)’);

echo $a; // it will output object id #1 (or another number)

echo $b; // it will output Better Class (b)

4. You can use chaining method calls. I’m not sure if there is some use of this, but the following code is valid:

class SomeClass {
public function Dev() {return $this;}
public function the() {return $this;}
public function Web() {return $this;}
}

$a = new SomeClass();
$a->Dev()->the()->Web()->…. // these three functions can continue to be chained.

5. You can prevent the Headers Already Sent error by omitting

the closing PHP tag ?>. This error may occur if you include a file that has the closing tag and extra line breaks inserted afterward. The good news is that omitting the closing tag is perfectly legal.

6. The associative arrays can be unpacked very easy using the extract method:

extract(array(‘a’ => ‘dev’, ‘b’ => ‘the’, ‘c’ => ‘web’));

echo $a; // dev
echo $b; // the
echo $c; // web

7. Rather than printing out to the page, there’s a printing function (print_r) that will return its result as a string. Just set its second parameter to true.

8. If you’re using php 5 with mysql 4.1 or later, you’d better

use the mysqli_ functions instead of the old mysql_ functions. Reason is that mysqli_ are just improved sql functions.

I hope you’ve found something useful in the examples above :)

P.S. You can check out also the First Part of Things You Probably Didn’t Know About PHP – HERE

Do you try to Find Things You Didn’t Know About PHP?
  1. 11 Comments to “Things You Probably Didn’t Know About PHP – Part 2”

    1. kodegeek says:

      __toString is magic method which is called while type casting of object.

      mysqli is another library such as PDO which is available in php 5 that support mysql advance features such as prepare statement.

    2. SeanJA says:

      I hate it when people do #2, such a pain in the ass to debug when you don’t realise it is happening.

    3. rICHARD@hOME says:

      #2 is generally frowned upon. Better to return an array if you have multiple return values:

      function doSomething($a, $b) {

      return array(“total” => $a + b, “sum” => $a * b);

      }

    4. Unomi says:

      I’m sorry but #1 is classic programming and without it you can get in some deep trouble. Can’t say this is a ‘tip’ or ‘trick’…

      And for the chaining (#4), there are classes out there that uses this technique quite well. I’ve seen it in test libraries, but in some high configurable factory patterns too. It helps a lot and I remember it is a speed gain too.

      – Unomi -

    5. ftsoc says:

      actually at #2, you aren’t returning values but passing values by reference, which means you change the passed variables when u do any op. on it. its a huge difference.

    6. A neater way to return multiple values is to use an array, either an associative array as one of commenter’s above sggested, or a simple array as follows…

      function foo() {
      return array(‘bar’, ‘baz’);
      }
      list($var1, $var2) = foo();
      echo ($var1); // bar;
      echo($var2); // baz

      Pass by reference parameters is something that a lot of languages support, but can be difficult to work with unless you know what’s happening. Given PHP’s great array support I;ve never had need to do it.

      Jim.

    7. Nandi says:

      #6 can be a security risk, because it overwrites your local variables. Never use it to unpack $_REQUEST, $_GET, $_POST.
      On the other hand it is quite useful in templates:
      function showTemplate($file, $params) {
      inlude ‘tempaltepath/’ . $file;
      }

      in the template:
      extract($params);

    8. Utahcon says:

      #5 is a bad practice, and should be avoided. Since this is non-standard and inconstant usage of matching opening and closing tags, it should be avoided. It is always best to write code that is correct then to try to work around problems in case the work around becomes invalid in some future version. Correct code will always be correct. Code with a work around solution in it often breaks again.

    9. SeanJA says:

      Glad I am not the only one that thinks that #2 is a horrible practice…

    10. Daniel says:

      @Utahcon: Omitting the closing ?> PHP tag is certainly neither bad practice nor non-standard. It’s required in the Zend Framework coding standards (http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html) for instance. Doctrine and symfony (two other large projects) use the practice of omitting the closing tag as well just to name a few.

      As for the rest of this article, you should be careful when you talk about things other people supposedly probably don’t know. I found all of these trivial and indeed most of them can be found in the manual.

    11. foobar says:

      the title of the article should be: “Things you probably didn’t know about PHP if you just started programming.”

    Leave a Reply