PHP Questions

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

PHP Question: Class Methods

4th May 2011 - 4 minutes read time


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

PHP Question: PHP Script Shape

1st May 2011 - 5 minutes read time


Write a PHP script that will print out the following text in the correct diamond shape.

PHP Question: Print Object

28th April 2011 - 3 minutes read time


The following code was executed.

  1. <?php
  2. class MyClass {
  3. private $foo = "bar";
  4. }
  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
  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 - 4 minutes read time


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 - 2 minutes read time


Consider the following:

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

What does the variable $a now equal?