PHP Questions

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

PHP Question: Post Variables

Question

Take the following HTML form.

1
2
3
4
<form id="form" name="form" method="post">
<input type="text" name="number" value="0" />
<input type="submit" />
</form>

What is the output of the following PHP code after the above form has been submitted, and why?

1
2
3
4
5
if ($_POST['number'] === 0) {
        echo 'number is zero';
} else {
        echo 'number is not zero';
}
Category: 

PHP Question: Print Object

Question

The following code was executed.

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

Which produced the following error.

1
2
3
4
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?

Category: 

Pages