PHP Questions

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

PHP Logo

PHP Question: Defining Constants

9th May 2011 - 5 minutes read time

Question

What does the following code do?


define("MY_CONSTANT", array(1,2,3,4,5));









 

Answer

If this code is run it will produce the following error:


Warning: Constants may only evaluate to scalar values in test.php on line x

This is because only scalar values can be assigned to constants. A scalar value is any integer, float, string or boolean value and does not include arrays, objects or resources. Trying to set any non-scalar value as a constant will produce this error.

PHP Logo

PHP Question: Class Methods

4th May 2011 - 5 minutes read time

Question

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

PHP Logo

PHP Question: PHP Script Shape

1st May 2011 - 6 minutes read time

Question

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


    *
   ***
  *****
 *******
*********
*********
 *******
  *****
   ***
    *

 

 

 

 

 

 

 

 

 

Answer

The diamond shape consists of 10 'levels' of stars. Each level consists of one or more stars and some whitespace that pushes the middle star into the middle of the line. Each line must also consist of an odd number of stars as an even number of starts can't have a middle star.

PHP Logo

PHP Question: Print Object

28th April 2011 - 4 minutes read time

Question

The following code was executed.

<?php
class MyClass {
  private $foo = "bar";
}

$myObject = new MyClass();
echo $myObject;

Which produced the following error.

Catchable fatal error: Object of class MyClass could not be converted to string in test.php on line 7

Call Stack:
    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 Logo

PHP Question: Form Variables

22nd April 2011 - 4 minutes read time

Question

Given the following form:

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

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

PHP Logo

PHP Question: Pass By Reference

19th April 2011 - 2 minutes read time

Question

Consider the following:

function doSomething(&$val) {
    $val++;
}

$a = 1;
doSomething($a);

What does the variable $a now equal?