PHP Questions

PHP questions suitable for use in interviews or just for fun.

PHP Question: Class Methods

4th May 2011

Question

What is the difference between these two lines of code and can you produce the background code used for them?

PHP Question: Print Object

28th April 2011

Question

The following code was executed.

  1. <?php
  2. class MyClass {
  3. private $foo = "bar";
  4. }
  5.  
  6. $myObject = new MyClass();
  7. echo $myObject;

Which produced the following error.

  1. Catchable fatal error: Object of class MyClass could not be converted to string in test.php on line 7
  2.  
  3. Call Stack:
  4. 0.0011 323736 1. {main}() /test.php:0

How can the code be simply changed to prevent this error and produce some form of result?

PHP Question: Form Variables

22nd April 2011

Question

Given the following form:

  1. <form method="post" action="index.php">
  2. <input type="input" value="" name="text" />
  3. <input type="submit" value="Submit" />
  4. </form>

How would you get hold of the value of the input box after the form is submitted?

PHP Question: Pass By Reference

19th April 2011

Question

Consider the following:

  1. function doSomething(&$val) {
  2. $val++;
  3. }
  4.  
  5. $a = 1;
  6. doSomething($a);

What does the variable $a now equal?