PHP Flashcards

1
Q

Define a query for MySQL using PHP?

A

mysqli_query($connection, $query);

(Query can be an insert, delete etc…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What function can we use for preventing SQL injection attacks on user input?

A

mysqli_real_escape_string($db, $string);

Old school way…

addslashes($string);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What function do we use to find out what the last connection error was in mysql?

A

mysqli_connect_error();

mysqli_connect_errno();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What function connects to a database?

A

mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What function to you use to determine what error occurred when performing database queries?

A

mysqli_error($connection);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What function do you use to close a connection with a mysql database?

A

mysqli_close($connection);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Given a query that returns a number of results, how to you iterate through the results?

$result = mysqli_query($connection, $query);

A
while ($subject = mysqli_fetch_assoc($result)) {
   // output the results
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What mysqli api will give you the count of a set?

A

mysqli_num_rows($set)

This can be useful for determining how many “of a thing” you have

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What kind of redirect does header() perform?

A

302 Redirect

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you redirect to a page, say “login.php”?

A

header(“Location: login.php”);
exit;

NOTE: That you don’t need the 302 status code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does a 302 status in the header do?

A

It tells the browser to do a second get request to the new location.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Why does session_start have to come at the start of a page?

A

Because if there isn’t a session, then it will create a cookie - which means modifying the header, and this must happen before ANYTHING is set in the page, much like a header() call.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How would you print the current year in php?

A

echo date(“Y”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How would you print the current year in php?

A

echo date(“Y”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How would you include a class definition file?

A

require ‘class.Definition.inc’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you instantiate a class?

A
$newclass = new Class;
$newclass = new Class();
// Both seem to call the constructor
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you unset a variable that has already been set?

A

unset($variable_name);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a magic method?

A

An internal callback that is triggered based on an event in a class - i.e. __set is triggered when you attempt to set a variable in a class (if it is inaccessible)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

When is __set(string $name, mixed $value) called?

A

When an inaccessible member is referenced (attempted to write to)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

When is __get($name) called?

A

When an inaccessible value is read from

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the equivalent of a constructor in PHP?

A

__construct()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

If you have a variable name stored in a variable. How do you access the variable that the name refers to (in a class)?

A

$this->$name

note the use of $ after the ->

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the best way to setup a __construct method if you expect to populate it from a database.

A

Have it populate variables via an array

foreach($data as $name => $value) {
if (in_array($name, array(‘time_created’,
‘time_updated’))) {
$name = ‘_’ . $name;
}
$this->$name = $value;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What magic method would you use to allow an object be printed as a string?

A

__toString()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

var_export is similar to var_dump, but how is it different?

A

It returns valid PHP code whereas var_dump does not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the scope resolution operator in PHP?

A

:: - same as C++

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How would you access a static variable named ‘foobar’ in a class named ‘Shoe’?

A

Shoe::$foobar;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is the best practise for naming constants in PHP?

A

Uppercase with underscores. MY_CONST

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do you declare a constant variable in a class in PHP?

A

const ADDRESS_TYPE = 1;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is the difference with const and standard variables when referencing them from outside a class?

A

You need to use the scope resolution operator and no $.

Shoe::MY_CONST;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

How do you get around the issue of $this not working with a static method?

A

Use self

self::$my_variable;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What PHP method can be used to determine if a value exists as a key in an array?

A

array_key_exists($key, $array)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is an autoload function?

A

It is a PHP function that attempts to automatically load class files for inclusion.

function \_\_autoload($class_name) {
   include 'class.' . $class_name . '.inc';
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How many classes can php extend at the same time?

A

Only one

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How do you declare a child class in PHP?

A

class ClassChild extends ClassParent {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How do you prevent a class from being instantiated?

A

Declare it as abstract

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

If a class has an abstract method, the class must be…

A

abstract

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

If an abstract class has a method…

A

the extending class MUST declare it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

How do you declare an abstract class?

A

abstract class myClass { }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How do you handle scope when implementing an abstract method in a child class?

A

You must have the same OR less restrictive scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Do interfaces have methods?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Can you use autoloading with interfaces?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

How many interfaces can a PHP class implement?

A

As many as required

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

How do you prevent a method from being overridden in subsequent classes?

A

Use the final keyword

final function myFunc() {…}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Can I change the visibility scope when overriding a method?

A

Yes, but you can’t make it stricter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Can I redeclare a method (override) that is in an interface?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

How many arguments can an overriding method have?

A

It must have the same number as the method being overridden (with exception to the __construct method where you can have more or less)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

How do you copy an object?

A

Use the clone operator

$obj = clone $myobject;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

How do you test that two objects are the same type and have the same contents?

A

Use the == operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

How do you test that two objects are the same object?

A

Use the === operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is one problem with using the clone operator?

A

Sometimes elements within the object must have say, time specific data - cloning it would copy a field like ‘time_created’ instead of instantiating the variable with the actual time created

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

How do you get around the copy issues related to the clone operator (i.e. some fields should not be copied and need to be instantiated at time of object creation)?

A

Use the __clone magic method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is a reference in PHP?

A

It’s similar to a pointer in c

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What does the function get_class do?

A

Returns the name of a class of an object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

How do you determine if an object is an instance of a particular class?

A

$object instanceof MyClass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How do you assign an object reference to a variable?

A

$myvar = &$myobject;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

If I convert an array to an object using typecasting, what is the result?

A

An object with elements named after the key / value pairs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

If I convert a string to an object using typecasting, what is the result?

A

An object with a single value called scalar containing the string.

(i..e var_dump((object) “yo”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What parameter to an exception is the error code?

A
The second
throw new Exception("message", 1000);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What is lazy initialisation?

A
Set variables in a class to NULL instead of initialising them when the object is created. Initialise them when they are called for - if it's null initialise and return, otherwise - if it has a value, return it. 
This way you don't waste resources say if you never actually connect to a database.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What is a factory method pattern?

A

Creates an object without ever naming the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

If you have an array which contains elements which use keys - what sort function should you use?

A

uasort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is the difference between uasort and usort?

A

uasort maintains the original keys in the array, whereas usort assigns new keys to each element as it’s reordered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What does the list function do?

A

It assigns values from an array to a list of variables.

$var = array(‘car’, ‘truck’);
list($one, $two) = $var;

$one and $two will now have ‘car’ and ‘truck’ assigned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

Write a filter expression that tests for a variable being an int and greater than one:

A

filter_var($_POST[‘id’], FILTER_VALIDATE_INT, array(‘min_range’ => 1));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

Taking an input called $_POST[‘value’], how would you prevent cross site scripting?

A

strip_tags($_POST[‘value’]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

How do you refer to a class ‘Foobar’, that is in the namespace ‘Hello’?

A

new Hello\Foobar();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Making reference to the namespace and calling Hello/Foobar each time is cumbersome - how can we remove this requirement?

A

use Hello\Foobar as Foobar;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

How do you register a class / method to perform autoloading functions?

A
spl_autoload_register('autloader', 'autoload');
or
spl_autoload_register(\_\_NAMESPACE\_\_ . '\foo::test');
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Is “require” a statement or a function?

A

Statement. It is therefore preferable to not use brackets when calling require.

I.e. require ‘foo’; NOT require(‘foo’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

How do you specify which error handler is used by PHP?

A

set_error_handler(‘name_of_error_handler’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

What function allows me to print a backtrace?

A

debug_print_backtrace()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

How and why would you change the save location for session data?

A

Security reasons. You can change it by calling:

session_save_path(‘mypath’);

before every call to session_start();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

In making a singleton - how would you prevent duplication of a class?

A

Make an empty magic method __clone()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

When using .htaccess to RewriteRule, how do you make sure variables can be sent in PHP via the URL?

A

make sure the rule has [QSA] added to the end (Query String Append).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

What is the difference between ‘ and “ when using variables in PHP?

A

A variable $var will be treated as literal between two ‘'’s and therefore print $var. However, between two ““‘s the variable is evaluated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

Why use { }’s with variables in strings?

A

Using { } allows complex evaluation of variables between strings. i.e. echo “$var[‘foo’]”; will not evaluate properly - it must be done like:
echo “ {$var[‘foo’]} “;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

What is the name of the pattern where all requests are routed through a single index.php file?

A

front controller pattern

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

What is one reason the function session_set_save_handler() would not work?

A

The php configuration is set to “session.auto_start”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

When using fwrite, what mode must the file be opened in (assuming system that differentiates between ascii and binary mode files)?

A

b or binary mode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

How would you make the first letter in a word / sentence uppercase?

A

ucfirst(strtolower($string));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

What is wrong with the following PHP code?

class MyClass {
  public $var1 = get_date();
}
A

It is not possible to set an attribute in a PHP class using an expression, it must be a literal value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

What class name can you NOT use due to it already being in use by PHP?

A

stdClass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

How do you delete an object once you are finished with it?

A

unset($object);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

Are class names case sensitive in PHP?

A

No (but object names obviously are, as they are variables).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q
What is wrong with the following?
class MyClass {
   public $var;
   function do() {
      print $var;
   }
}
A

$var is not accessible in that method - you need to use…

$this->var;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

If PHP can’t find a constructor called __construct, what will it look for next?

A

A constructor with the same name as the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

How do you create a destructor in PHP?

A
function \_\_destruct() {
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

When is a destrutor called on an object?

A

When it is destroyed (i.e. use unset($obj);)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

Can a destructor take arguments?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

What is the purpose of the __autoload special function?

A

It is used to load automatically any class / file definitions that are required by a class.

function \_\_autoload ($class) {
require ($class . '.php');

When a class is invoked, it automatically includes it’s own definition file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

Is __autoload part of a class definition?

A

No - it’s typically placed in the script where the classes are to be instantiated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

What is the phpdoc syntax for a var tag?

A

@var type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

What is the phpdoc syntax for a parameter tag?

A

@param, and @return

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

What is pear?

A

PHP Extension and Application Repository

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

How would you get phpdoc to document an entire project?

A

phpdoc -d . -t docs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

Is the destructor of a parent class automatically called when a child object is destroyed?

A

No - (unlike some other OO languages)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

When overriding a method in a child class, what must the signature of the method be?

A

The same as the parent that you are overriding

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

Protected methods / variables are available to who?

A

This class and derived classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

Can you directly access a protected member via an object?

A

no

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

How do you refer to a variable / method in a parent class?

A

parent::doThis();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

Why should you use static:: over self::

A

static implements late static binding - which can prevent issues such as self:: refering to the scope that was present when the parent class was defined (i.e. calling the method you didn’t expect).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

When should you use self::

A

When you want to refer to a method within that class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

Class constants are like static variables in what way?

A

They are available across all instances of a class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

Can a class constant be modified?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

Can a class constant’s value be based on another variable?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

Can you access a class constant through the object?

A

No - it must be accessed through the class

classname::attribute;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

Can a static variable be accessed within a class using $this?

A

No, you must use self:: or static::

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

How do you call a static variable within the class?

A

self: :$var;
static: :$var;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

What is different about accessing a static attribute vs static method via an object?

A

A static attribute cannot be accessed via an object (but a static method can be).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

How would you call the parent destructor or constructor from a PHP class?

A

parent: :__construct()
parent: :__destruct();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
112
Q

What type of functions is $this not available in?

A

static

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
113
Q

Does a class with an abstract method in PHP have to be declared as abstract?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
114
Q

What feature must all methods in an interface have?

A

They must all be public.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
115
Q

What PHP function can be used to create a unique user ID?

A

uniqid();

Keep in mind it’s not truly random, so security is a concern

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
116
Q

What is on distinction between an interface and a class (regarding inheritence)?

A

A class can implement multiple interfaces, while a class can only extend a single parent class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
117
Q

What kind of copy does the clone operator do in PHP?

A

By default it’s a shallow copy - to customise this use the __clone magic function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
118
Q

What do traits allow?

A

Provides functionality to a class, as if it had inherited from multiple parents.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
119
Q

Can you instantiate a trait?

A

No (like interfaces and abstract classes)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
120
Q

How do you create a trait?

A
trait tSomeTrait {
   function doSomething() {
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
121
Q

How do you add a trait to a class?

A

Use the “use” keyword.

class newClass {
   use tSomeTrait;
}

newClass now has access to the functions declared within tSomeTrait

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
122
Q

What function could you use to get a list of methods in a class?

A

get_object_methods($this);)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
123
Q

What function could you use to get a list of variables in a class?

A

get_object_vars($this);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
124
Q

If a trait and a class have a method with the same name, which one takes precedence?

A

The class method, unless it was inherited from another class - in which case the trait method will take precedence.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
125
Q

What is type hinting?

A

It is where you suggest a type (in PHP oop) - as a parameter. The type must be obeyed or it generates a fatal error.

class SomeClass {
  function doThis(OtherClass $var) { }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
126
Q

Does type hinting work with scalar types?

A

No, only objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
127
Q

Can type hinting be used in functions?

A

Yes - it doesn’t have to be within a class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
128
Q

What can be hinted?

A

Classes, functions (5.4) interfaces and arrays (5.1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
129
Q

What version of PHP added support for namespaces?

A

5.3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
130
Q

What are the only things that can be stored in a namespace?

A

Classes, Interfaces, Functions and Constants.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
131
Q

Namespaced code should live in it’s own…

A

file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
132
Q

In a namespaced file, what is the first thing that should appear in the file?

A

namespace NameofYourNamespace;

(NOTE: HTML must not come before the namespace declaration). (2nd NOTE: namespace can come after the PHP declare() statement)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
133
Q

Namespaces can have subnamespaces, how would you organise that?

A

namespace MyUtilities\UserManagement;

class Login { }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
134
Q

You have a class called Department in a namespace called MyNamespace - how do you actually reference it?

namespace MyNamespace\Department;

A

$var = new \MyNamespace\Department();

(NOTE the leading slash, which doesn’t appear in the declaration).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
135
Q

Can the same namespace span multiple files?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
136
Q

What PHP constant represents the current namespace?

A

__NAMESPACE__

137
Q

What keyword can reduce the amount of typing when dealing with namespaces?

A

use

use MyNamespace\Company;

138
Q

What can you do to prevent a user creating multiple singletons?

A

Set the access level of the __construct and __clone functions to private

139
Q

Can you test more than one parameter with isset()?

A

Yes, isset($var1, $var2); will only return true if all parameters are set (it’s unlimited number of parameters.

140
Q

What two user defined methods are required for a composite pattern?

A

Add and Remove

141
Q

What function would you use to find the index of an object in an array?

A

$index = array_search($e, $array);

142
Q

What is the error surpression operator?

A

@

i.e. @fopen($file, ‘w’);

143
Q

Is it appropriate for a constructor to throw an exception if required?

A

Yes

144
Q

Can a catch block throw an exception?

A

Yes, and it can be caught by a subsequent catch block

145
Q

What PHP function can be used to determine if a file is writable?

A

is_writable($file);

146
Q

If you create an extended Exception class, what should it do?

A

It should call the parent constructor

parent::__construct

147
Q

What is PDO?

A

PHP Data Object

148
Q

How do you determine what applications are supported by PDO?

A

print_r(PDO::getAvailableDrivers());

149
Q

How do you create a PDO for MySQL?

A

$pdo = new PDO(‘mysql:dbname=test; host=localhost’, ‘username’, ‘password’);

NOTE the way the dbname and host is passed

150
Q

Once you’ve finished with a PDO, how do you delete / close the connection?

A

unset($pdo);
or
$pdo = NULL;

151
Q

PDO being an object doesn’t have errors, but rather throws exceptions - what type of exception?

A

PDOException

try {
} catch (PDOException $e) {
}

152
Q

What PDO method is typically used to run queries that do not return a result (i.e. INSERT, UPDATE, DELETE)?

A

$pdo->exec($q);

153
Q

What PDO function can you use to change the error reporting level for your database?

A

PDO->setAttribute

154
Q

What would you call if, after running a PDO insert, you wanted to know the dynamically generated primary key value?

A

$id = $pdo->lastInsertId();

Equiv to mysqli_insert_id()

155
Q

What is the PDO equivalent of mysqli_real_escape_string() to prevent MySQL injection attacks?

A

$data = $pdo->quote($unsafe_data);

156
Q

Other than preventing sql injection attacks, what else does $pdo->quote() do?

A

It wraps the data in quotes, meaning you don’t have to in the query.

157
Q

What does $pdo->exec() return?

A

0 if nothing is affected, FALSE if there was an error. A positive number (number of rows affected) if rows are affected.

158
Q

What PDO method do you use to run a query that does return a result?

A

$result = $pdo->query($q);

159
Q

What does $pdo->query($q) return?

A

A PDOStatement object

160
Q

How do you determine how many rows where affected after a $pdo->query($q) call?

A

$results->rowCount() (which is equiv to mysqli_num_rows()

161
Q

I have used a $pdo->query and obtained $results. How do I process these results?

A

Use PDOStatement::fetch()

$results->fetch()

162
Q

I can’t use fetch straight away, I need to tell PHP how to fetch the records, how do I do this?

A

$pdo->setFetchMode()

Pass the options

PDO::FETCH_ASSOC
PDO::FETCH_NUM
PDO::FETCH_OBJ
PDO::FETCH_CLASS

163
Q

There is another way to fetch results - without using fetch, how do you do this?

A
foreach($pdo->query($q) as $row) {
   // Use row
}

// NOTE Under the hood, it is NOT running the query multiple times

164
Q

Using PDO write a basic query to select username from a table called users.

A
$results = $pdo->query('SELECT username FROM users');
$results->setFetchMode(PDO::FETCH_NUM);
while ($row = $results->fetch()) {
  // $row[0] will be the first column in the output
}
165
Q

By default, PHP will do what before calling the __construct function of an object when building an object (i.e. PDO::FETCH_CLASS)?

A

It will map the columns to variables within the class. If the variable does not exist as per the column, it will create a new one. Keep this in mind as it may cause an issue with $_id and ‘id’ in the database (i.e. PHP will create a new variable $id).

166
Q

What is one benefit of using a prepared statement when dealing with databases?

A

Because data is sent separately, you don’t have to guard against injection attacks (it is handled for you).

167
Q

Write a prepared statement to select everything from a users table given an email address:

A

$stmt = $pdo->prepare(‘SELECT * FROM users WHERE email=?’);

168
Q

What is the placeholder indicator in a prepared statement?

A

’?’ character represents data to be replaced in the statement.

169
Q

What is the other way (other than using ?) to write a placeholder in a PDO prepared statement?

A

Use a named placeholder
prepare(‘SELECT * FROM users WHERE email=:email’);

NOTE: the “:email” this will correspond to a key in an array that is used to pass the data.
array(‘:email’ => ‘cain.martin@gmail.com’);

170
Q

Why are prepared statements so useful?

A

They have a large performance boost (especially when the same statement is repeatedly called with only the data changing)

171
Q

What version of PHP is the SPL no longer able to be disabled?

A

5.3

172
Q

What is the SPL?

A

Standard PHP Library

173
Q

What class (in the SPL) would you use to define your own Session Handling object?

A
SessionHandlerInterface
(an interface that defines a set of functions required to handle sessions)
class SessionHandler implements SessionHandlerInterface { }
174
Q

How would you make PHP use your session handler object?

A
$sh = new SessionHandler();
session_set_save_handler($sh, true);
175
Q

What class is useful for getting information about a file?

A

SplFileInfo($filename);

  • > getBasename()
  • > getExtension
  • > getMTime
  • > getSize
  • > getType
  • > isDir
  • > isFile
  • > isWritable
176
Q

If you want to write or change a file, what SPL class can you use to do this?

A

SplFileObject

NOTE: SplFileObject inherits from SplFileInfo - so it has it’s functionality too.

177
Q

In procedural PHP you have to close a file stream, when does the stream get closed with an SplFileObject object?

A

When the object is deleted.

178
Q

While it’s useful to be able to create your own exception classes, which ones should you use for best compatability between your code and extenal code?

A

The exception classes that are defined in the SPL

179
Q

What SPL interface is useful for creating a method for looping through instances of a class?

A

Iterator

180
Q

If I have a DirectoryIterator, what iterator can I use with it to limit the types of files that are iterated over?

A

FilterIterator

181
Q

What SPL class offers better performance (but more limited functionality) when it comes to arrays?

A

SplFixedArray

182
Q

What SPL class implements a stack data structure?

A

SplStack

183
Q

What SPL class implements a FIFO data structure?

A

SplQueue

184
Q

Write a function that autoloads classes as they are required?

A
function class_loader($class) {
  require ('classes/' . $class . '.php');
}

spl_autoload_register(‘class_loader’);

185
Q

What interface would you use on a class if you wanted it to be accessible in much the same way an array is?

A

ArrayAccess

186
Q

What interface would you use on a class if you wanted to use the count function on it?

A

Countable

187
Q

What is the syntax for multiple interfaces?

A
class Department implements Iterator, Countable {
}
188
Q

What is the purpose of serialisation?

A

To convert complex data into a more digestable format for say, a database to store.

189
Q

An array may have in it’s serialized data something like s:5:”karen”, what does this mean?

A
s = string
5 = number of characters
"Karen" = the data in the array
190
Q

When data has been serialised, how do you convert it back to it’s original form?

A

unserialize($sData);

191
Q

Are a methods methods stored when an object is seralized?

A

No (but they come back when it is unserialized)

192
Q

What do we have to keep in mind when unserializing data?

A

You must have access to the class definition that you are unserializing too.

193
Q

When are objects automatically serialized / unserialized?

A

When storing an object in a session

194
Q

Say you want to grab a section of data for a page from the database as a preview (i.e. first 200 characters) - but the text may include image links etc. What do you run over the data to remove any of that stuff?

A

strip_tags()

195
Q

If we are using PDO::FETCH_CLASS and a query has DATE_FORMAT(dateAdded, “%e %M %Y”)… what will happen when the data is written to the subsequent object after the query?

A

There will be no dateAdded field in the class - to solve this use an alias:
DATE_FORMAT(dateAdded, “%e %M %Y”) AS dateAdded

196
Q

In MVC the view does what?

A

All the handling of the data display.

197
Q

Can PHP appear in the View?

A

Yes - but typically very minimal and only for doing formatting and data extraction stuff.

198
Q

How do you open a connection to another website in PHP?

A

fopen(‘http://fuckingwebsite.com/index.php’, ‘r’);

NOTE: only ‘r’ will work of course

199
Q

What function(s) is used to open a socket connection to a site?

A

fsockopen or fopen

200
Q

What variable can be used to determine a users IP address (actually the ISP’s)?

A

$_SERVER[‘REMOTE_ADDR’]

201
Q

How do you initiate a cURL session?

A

$curl = curl_init($url);

202
Q

When developing a service, the PHP script must tell the client what?

A

What format the data is in

203
Q

How do you tell a client what format the data is in?

A

header(‘Content-Type: text/plain’);
header(‘Content-Type: text/xml’);
header(‘Content-Type: application/json’);

204
Q

How do you encode data into Json in PHP?

A

echo json_encode($data);

205
Q

How do you open a file to write compressed data to it?

A

$fp = gzopen(‘filename.gz’, ‘w5’);

The w is the same w as in opening binary / text files. The 5 is the level of compression that the file should receive

206
Q

How do you write to a file, that will be compresed?

A

gzwrite($fp, ‘data’);

// later
gzclose($fp);
207
Q

What two functions can be used to read from a compressed file?

A

readgzfile()

gzfile()

208
Q

Assuming an empty directory, what is wrong with the following code?
mkdir(‘backup/test’, 0777);

A

A nested structure was passed as an argument. In order to create a nested directory structure the recursive option must be true.
mkdir(‘backup/test, 0700, true);

209
Q

What library can I use to encrypt data?

A

mcrypt

210
Q

What function can I use to get a list of supported mcrypt encryption algorithms?

A

$algos = mcrypt_list_algorithms();

211
Q

What is an IV?

A

Initialisation Vector - input into a cryptographic primitive.

212
Q

How do you create an IV in PHP?

A

$m = mcrypt_module_open(‘rijndael-256’, ‘’, ‘cbc’, ‘’);

$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($m), MCRYPT_DEV_RANDOM);

213
Q

For a 256 bit key, you require 32 character string to create a key (8 bits in a byte, 32 characters in 256). What is one way to create a key (it should be random, very hard to guess)?

A

Use md5 to generate a key from a random string. MD5 always returns a 32 character string.

$key = md5(‘some string’);

214
Q

Once you have created your IV - what is the next step mcrypt requires?

A

Create buffers so mcrypt can work with them. mcrypt_generic_init($m, $key, $iv);

Where..

$m - encryption descriptor
$key - key (generate with md5)
$iv - Initialisation Vector

215
Q

What function is used to encrypt data once mcrypt is setup?

A

$encrypted = mcrypt_generic($m, $data);

216
Q

How do you cleanup after using mcrypt?

A

mcrypt_generic_deinit($m);

mcrypt_module_close($m);

217
Q

What function is used to decrypt data having been encrypted with mcrypt?

A

$data = mdecrypt_generic($m, $encrypted);

218
Q

What must the same in order to decrypt data?

A

The key and the IV (initialisation vector)

219
Q

What functions should you use if you have to pass non-hardcoded functions to a system command?

A

escapeshellarg() or

escapeshellcmd()

220
Q

What is one of getting input back from the command line?

A

Using backticks (i.e. $var = ls; will run ls on the command line and return the results).

221
Q

Which function, like system(command) can return input from the command line but in binary format?

A

passthru();

shell_exec(command);

222
Q

What’s one reason shell_exec, exec, or system may fail?

A

The external app being run may require more memory than allowed by PHP.INI (look for memory_limit)

223
Q

How do you run php in a pseudo web server mode from CLI?

A

php -S localhost:8000

Then connect to it through a web browser “http://localhost:8000/script I want to run”

224
Q

How do you create a new Expat parser for XML?

A

$p = xml_parser_create();

225
Q

Expat is an …. XML parser?

A

event based

226
Q

What is the limitation of using Expat?

A

It is event based, so you can only get access to certain elements (such as attributes) when you come across them in the file.

227
Q

What is a more flexible system for parsing XML?

A

simplexml

228
Q

What function can you use to get information (size, type) so it can be used in HTML?

A

getimagesize(nameoffile);

229
Q

How do you load an xml file and parse it using simplexml?

A

$xml = simplexml_load_file(‘nameoffile.xml’);

foreach($xml->mynode as $mynode) { // do things }

230
Q

What is the trick with comparing XML data as an XML string?

A

XML elements and attributes are treated as objects, so you need to cast them to strings if you want to compare them (or use them in any standard string functions)

231
Q

Which of the XML parsers supports XPath?

A

SimpleXML

232
Q

What is a downside to using DOM parsers (simple XML)?

A

It uses more information than the SAX parsers on the server, as it stores the entire document in a variable.

233
Q

xdebug can be used to see the superglobals - how does this work?

A

Use ini_set to configure what you see
ini_set(‘xdebug.dump.SERVER’, ‘*’);
xdebug_dump_superglobals();

234
Q

Using PHPUnit, which function can be added to a test class to ensure the ‘fixtures’ are in place?

A

setUp() { }
And use
tearDown() { } to clean up

235
Q

What class does a class extend from to use UnitTesting?

A

PHPUnit_Framework_TestCase

236
Q

What does the end / prev functions do?

A
Act as iterators on an array
$value = end($array);
while ($value) {
   $value = prev($array);
}
237
Q

What function can be used to walk an array and perform a user defined action on it?

A

array_walk()

238
Q

What function would you use to get a count of how many times each UNIQUE value occurs in an array?

A

array_count_values

239
Q

How could you write a conditional statement that ensured the parameter passed was of type MySQLi?

A

if ($instance instanceof MySLQi) { }

240
Q

If a derived class does not have a constructor, are the parent class constructors automatically called?

A

Yes. If the child DOES have a constructor, it will have to manually call the parent constructor.

241
Q

Function overloading (differentiating by parameter types) does not work in PHP - how could you get away with it so you can configure different objects based on parameters?

A
class Student() {
   public \_\_construct() {
      // Do configuration here
   }
   public static function withID($id) {
      $instance = new self();
      // Do stuff with ID
      return $instance;
   }
   public static function withoutID() {
      $instance = new self();
      return $instance;
   }
}

$student = Student::withID(30230);

242
Q

How do call the constructor for the current class (i.e. to create itself)?

A

$_instance = new self();

Using self();

243
Q

Static methods cannot access…

A

properties in a class (just static members)

244
Q

Can an object be assigned to a constant?

A

No, only primitive types

245
Q

How do you refer to a constant in code?

A

self: :CONSTANTNAME; or
classname: :CONSTANTNAME;

246
Q

What is the one case in which a derived class doesn’t have to implement all the methods in an abstract parent class?

A

When it itself is abstract.

247
Q

How do you use multiple traits in the one class?

A

One after the other with commas.

trait traitClass1, traitClass2;

248
Q

If a class implements an interface, under what condition does that class not have to directly implement the interface?

A

If it uses a trait that implements it on the classes behalf.

249
Q

If I have two traits, PriceUtilities and TaxTools, both with a calculateTax method - how could I avoid a method naming conflict?

A

use PriceTools, TaxTools {
TaxTools::calculateTax insteadof PriceUtilities;
}

Use the insteadof keyword.

250
Q

If you have two traits, PriceUtilities and TaxTools, both with calculateTax method, how could you use both of them in a class witout method conflicts?

A

Use the ‘as’ aliasing keyword

use PriceUtilities, TaxTools {
TaxTools::calculateTax insteadof PriceUtilities;
PriceUtilities::calculateTax as basicTax;
}

Now you can use basicTax as a method of the enclosing class.

251
Q

When using the ‘as’ keyword to alias a method in a trait, what MUST you do as well?

A

Make sure there are no ambiguities. So the first thing to do is define WHICH method will be the one to use, using ‘insteadof’, THEN you can use ‘as’ to alias the other method.

252
Q

What else can the ‘as’ keyword be used for?

A

You can use it where there is no clash to alias a trait method, perhaps so it can implement an abstract method signature in a parent class.

253
Q

How are static methods accessed via a trait?

A

The usual way - there is no difference

254
Q

Can traits access properties in a host class?

A

yes - but it’s VERY bad design (as it binds the trait class to the host class in a way that’s not very flexible)

255
Q

Can you change the access level of a trait in a host class?

A

Yes - using the ‘as’ operator
use PriceUtilities {
PriceUtilities::calculateTax as private;
….

256
Q

What would the problem be with moving a create function to the superclass, if it uses the self:: keyword?

A

self refers to the context of resolution, NOT the calling context. So it would be effectively like parent::create, and not $this::create

257
Q

What does the static() keyword do?

A

It allows late static binding. So it refers to the invoked class, rather than the calling class. So you can put a “create” method in a superclass, and when calling it from the subclass, it tries to create the subclass, rather than the doomed to fail creation of the superclass (containing class).

return new static(); // This is how you use it

258
Q

What version of PHP did static keyword (for late static binding) come in?

A

5.3

259
Q

What else can you use static keyword for?

A

It could be used to invoke static methods such that in a class hierarchy, the static method could be overridden, and the correct method would be called.

260
Q

What does file_put_contents do?

A

It writes data to a file, and is equivalent to calling fopen, fwrite and fclose in succession.

261
Q

What function can you use to load XML data?

A

simplexml_load_file($filename)

262
Q

What function converts a string into XML?

A

public mixed SimpleXMLElement::asXML($data)

263
Q

Given a SimpleXMLElement, what function could you use to search for one of the XML elements?

A

SimpleXMLElement::xpath(“xpath expression”);

264
Q

What does the basename function do?

A

Returns the trailling name component of path.
i.e. bsaename(“/etc/sudoers.d”, “.d”) returns
sudoers

265
Q

What is the rule of thumb when using multiple catch clauses?

A

Use the most specialised first, and generic last - otherwise they will always be caught by the generic exception.

266
Q

When using customised exceptions - it’s always a good idea to have one last catch clause to catch what?

A

Exception objects - as a last ditch barrier to errors.

267
Q

What version of PHP did the finally clause appear in?

A

5.5

268
Q

How would you prevent a class called ‘Checkout’ from being inherited from?

A

final class Checkout { }

269
Q

How would you prevent a method called foobar from being overriden in a subclass?

A

public final function foobar() { }

270
Q

What is an interceptor method?

A

The magic functions __get / __set are examples of interceptor methods. Interceptor methods are triggered when a message is sent to an undefined method or property

271
Q

What function can be used to determine if a method exists in a php object?

A

method_exists($this, $method)

272
Q

When does the __isset intercept method get called?

A

When a user uses isset() on a property that doesn’t exist.

273
Q

Why would you use __isset in conjunction with __get

A

For example, if you setup the __get interceptor method to call a get method instead of the private property name, you can use __isset to validate the same property.

274
Q

Why should a class that uses interceptor methods document this fact very clearly?

A

For instance, when using __call interceptor method for delegation, an object may receive another object, and the __call method is used on the first object to route (delegate) calls to that second object. This may not be clear from the interface, and resists reflection techniques.

275
Q

What is delegation?

A

Where one object passes on method invocation onto a second object. In PHP this can be achieved (among other ways) via the __call interceptor method

276
Q
class CopyMe{}
$first = new CopyMe();
$second = $first;

How do these statements differ between PHP 4 and 5?

A

In 4, $first and $second are two distinct objects. In PHP 5 they refer to the same object.

277
Q

Why is using the clone operator (with __clone intercept method)?

A

Sometimes you want two copies of an object, but in particular, using __clone allows you to control how things are copied. For instance, doing a straight clone will copy everything, including an id that may be used in database lookups, that needs to be unique, so __clone can be used to customise the copy and take care of that.

278
Q

Where does the __clone method run, the copied, or original object?

A

The copied object.

279
Q

How are properties copied in an object when cloning?

A

primitive objects are shallowed copy, but object properties are copied by reference.

280
Q

How do you solve the issue that an objects property of type object may be copied by reference?

A

Make sure to implement a __clone intercept method and clone the object properties so that they are each individuals.

281
Q

What function can you use to test if a callback is callable?

A

is_callable()

282
Q

Why might you want to add callback functionality to your objects?

A

By making a component callback aware, you give others the power to extend your code in contexts that you don’t know about yet.

283
Q

If you wanted to pass a function around via a variable, what is one way to do this via inbuilt php functions?

A

Use create_method

$logger = create_function(‘$product’, ‘print “ logging({$product->name})\n”;’);

284
Q

Creating a function via create_function uses … functions.

A

anonymous

285
Q

create_function is one way to create an anonymous function - what is another way (post PHP 5.3)?

A

$logger = function ($product) {
print “ logging ({$product->name})\n”;
}; // Note the ‘;’ at the end!!!!

286
Q

How would I go about sending an object method to a callback register function (it will be tested by is_callable())?

A

$myObj->registerCallback(array(new Obj(), “myMethod”));

NOTE: is_callable is smart enough to deal with an array. An object should be the first element of the array and name of the method is it’s second argument.

287
Q

How can a function be returned from a function (like a function factory)?

A
return function ($product) {
   if ($product->price > 5) {
      print "Stuff is expensive now... {$product->price}\n";
   }
}
288
Q

What is a closure?

A

A function, or reference to a function together with a referencing environment (i.e. variables that are non-local to the function, but still accessible due to a table comes along with the function)

289
Q

How do you implement a closure in PHP?

A
class Totalizer {
   static function warnAmount($amt) {
      $count = 0;
      return function ($product) use ($amt, &$count) {
         $count += $product->price;
         print "     count: $count\n";
         if ($count > $amt) {
            print " high price reached: {$count}\n";
         }
      }; // End of closure / return function
   } // End of warmAmount function
} // End of Totalizer class

NOTE: This is useful because $count can keep track between invocations (as a callback) of the total coun.

290
Q
What is the difference between:
file1.php
namespace main;
com\utils\Debug::helloWorld();
file2.php
namespace main;
\com\utils\Debug::helloWorld();;
A

The first one (in file1.php) is using a relative namespace, starting at main, and looking in com\utils etc.
The second one, is explicitly stating, search from the root.

291
Q
If I have a class Debug in a namespace com\getInstance\util\ how would I call a Debug method if I made use of the 'use' statement like such:
use com\getInstance\util;
A

util\Debug::myMethod();

292
Q
If I have a class Debug in a namespace com\getInstance\util\ how would I call a Debug method if I made use of the 'use' statement like such:
use com\getInstance\util\Debug;
A

Debug::myMethod();

293
Q

If I make visible a class called debug by using the ‘use’ statement - but I already have a class named debug in scope - I will get an error - how do I avoid this?

A

use com\utils\Debug as uDebug;

Now I can use the alias, uDebug.

294
Q

If I have an object called “Lister” in the local namespace, and I also have one in the global namespace, how do I differentiate?

A

Lister::myMethod(); // Calls local version

\Lister::myMethod(); // Calls global version

295
Q

Is it possible to have multiple namespaces in a single file/

A

Yes - make sure you use the braces - and you can’t use a mix of the line / braces syntax in the same file.

296
Q

One method of referencing classes from code is to use require_once with an absolute or relative path - but this is messy. How else could you simplify this?

A

Use the include_path value in php.ini to specify the folder where PHP can find them.

297
Q

How can you set the include path programatically?

A

set_include_path( get_include_path() . PATH_SEPARATOR . “/home/mycoolproj/phplib/”);

298
Q
You can use a string to instantiate a class name. How would you do that given:
$classname = "foobar";
A

$newObj = new $classname();

299
Q

What function can you use to get a list of all classes defined in a script process?

A

get_declared_classes();

300
Q

Why would you use the ::class operator?

A

It gives the fully qualified class name - which can be useful when writing functions that may have to deal with different namespace structures etc.

301
Q

How do I obtain a list of all the methods on a class?

A

get_class_methods(“class”);

302
Q

How could I test whether a method exists in a class using in_array?

A

if (in_array($method, get_class_methods($obj))) {

}

303
Q

What is the best way to determine if a method name is valid?

A

if (is_callabel(array($product, $method)) {
$product->$method(); // Note the $ in front of method
}

304
Q

What is the equivalent function to get_class_methods() for getting a list of properties from an object?

A

get_class_vars(“classname”);

NOTE: Like get_class_methods - it requires the name of a class passed as a string

305
Q

How would you find out the name of a parent class?

A

get_parent_class(‘classname’);

306
Q

What is the opposite of get_parent_class() (i.e. subclass)?

A

is_subclass_of($object, ‘classname’); // Returns true if $object is a subclass of classname

307
Q

Can is_subclass_of be used to determine if a class implements an interface? If Not, what should be used?

A

No it doesn’t - you should use instanceof operator.

308
Q

It is possible to call a method using a string by affixing the $ on the beginning
$method = “myFunc”;
$obj->$method();
What is another way of doing this?

A

call_user_func(array($obj, “myFunc”)); // or if you have defined a variable to hold “myFunc”
call_user_func(array($obj, $method));

309
Q

If you have a variable number of arguments, how could you use call_user_func?

A

Don’t - use call_user_func_array.

call_user_func_array(array($obj, $method), $args); // Where $args is an array of arguments.

310
Q

What class is useful for determining information about a class?

A

ReflectionClass
ReflectionMethod
etc.

311
Q

How would you use reflection to get information regarding a class/

A
$foobar_class = new ReflectionClass('foobar');
Reflection::export($foobar_class);
312
Q

ReflectionClass has a number of useful functions for determining information about a class, name some.

A

ReflectionClass::getName();
ReflectionClass::isUserDefined();
ReflectionClass::isAbstract();
ReflectionClass::isInterface();

313
Q

What is the caveat with ReflectionMethod::returnsReference()?

A

It doesn’t return true if an object simply returns an object (which is a reference) - it must be declared as a method that returns a reference by using the ampersand in front of the method.

314
Q

How do you get the class that refers to a methods parameters?

A

ReflectionMethod::getParameters(); which returns a ReflectionParameters object.

315
Q

What is one sign that the code design requires more polymorphism?

A

Use of conditionals to test for certain behaviors, especially when duplicated across methods. (i.e. if XML do this, if TEXT do that. Break it out into concrete versions of an XML class and Text Class)

316
Q

What’s one way to prevent performance issues when using reflection?

A

Cache the results if you know the values wont change (for instance when creating a pseudo enum class which contains fixed constants).

317
Q

What is one strategy to create configuration settings for your applications?

A

Use a script called settings and set some static variables containing the settings in there.

Then use a singleton object, something like ‘AppConfig’ to read the settings and create the appropriate objects.

318
Q

What does a composite pattern seek to do?

A

Allow a client to treat all objects the same way - despite being individual instances, or aggregates. For instance a unit may have a bombardStrength method, so will an Army object - which will also contain an aggregated list of “Unit”.

Both the composites and the ‘leaves’ will inherit the same interface, so the client can treat them the same way.

319
Q

What does the array_udiff function do?

A

Computes the difference between two arrays by using a callback function.

320
Q

What is the one issue with the composite pattern with regards to composites and leaves sharing the same interface?

A

The leaves must also implement the addUnit and removeUnit methods even though they are not aggregators.

321
Q

If a class inherits from an abstract class, and does not define a constructor itself - does the sibling inherit the parents constructor?

A

Yes, and the appropriate parameters must be passed.

322
Q
The following code is an example of...
function getWealthFactor() {
  return $this->tile->getWealthFactor();
}
A

Delegation

323
Q

What built in objects are used to facilitate the Observer pattern in PHP?

A

SplObserver (maps to what I would consider Observer)

SplSubject (maps to what I would consider Observable)

324
Q

In a typical Observer pattern, the Observable needs to keep a list of Observers. Using SPL what object would you use to create this storage?

A

$storage = new SplObjectStorage();

325
Q

What does clearstatcache do?

A

It’s a function that is used to clear the state of files on the file system. PHP caches states of files, but because they COULD be removed, you should use clearstatcache if this potentially a problem.

326
Q

What does filemtime() do?

A

Gets the file modification time

327
Q

If you are serializing objects, not everything can serialize, give an example?

A

Resources, such as database connections - you have to destroy the connection and re-establish it when you create the unserialized object

328
Q

What two magic methods are useful for serialisation of objects that have resources attached?

A

__wake and __sleep. You can for instance shutdown a database connection in the sleep - and re-establish it in the __wakeup

329
Q

What filter (using filter_var) can be used to clean up a URL?

A

filter_var($url, FILTER_SANITIZE_URL);

330
Q

Is ‘=& $variable’ and ‘= &$variable’ the same thing?

A

Yes, they are.

(BUT: note that ‘=&’ should be used together in a ternary operation. i.e.
isset($field[0]) ? $f =& $field[0] : $f =& $field;

331
Q

Does executable code in a file that is included, get executed?

A

Yes

332
Q

What kind of arrays cannot be directly converted into JSON?

A

Pure arrays, i.e. ordered, numerical index

333
Q

What is the only data type that cannot be converted using JSON?

A

A resource type

334
Q

What happens with private variables in an object when passing to json_encode?

A

They are ignored, only public variables get converted to JSON

335
Q

What method would you write to serialize an object to json (and preserve private vars)?

A
Write a public method called JsonSerialize (and implement the JsonSerializable interface):
public function JsonSerialize() {
  $vars = get_object_vars($this);
  return $vars;
}
336
Q

When writing an exception, sometimes we want to throw a specific exception, REGARDLESS of the type of exception that was originally caught - how would we do this?

A
try { // Try stuff } catch (Exception $e) { 
  $message = "Could not connect: " . $e->getMessage();
  throw new MyException($message, $e->getCode()); 
}

NOTE: we are re-throwing the exception here - but catching the original exception with the most generic exception type first.

337
Q

When using PDO in a namespaced class, you must refer to the PDO as \PDO. Having done this - you create a database with new and it throws an exception - but your code “catch(PDOException $e)” fails to catch it - why?

A

Even though you have included \PDO, you need to include the exception too.

catch (\PDOException $e) { // NOTE the slash in front of PDO Exception }

338
Q

What is the risk of not catch exceptions correctly with PDO?

A

You could expose your password to the database.