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
var_export is similar to var_dump, but how is it different?
It returns valid PHP code whereas var_dump does not.
26
What is the scope resolution operator in PHP?
:: - same as C++
27
How would you access a static variable named 'foobar' in a class named 'Shoe'?
Shoe::$foobar;
28
What is the best practise for naming constants in PHP?
Uppercase with underscores. MY_CONST
29
How do you declare a constant variable in a class in PHP?
const ADDRESS_TYPE = 1;
30
What is the difference with const and standard variables when referencing them from outside a class?
You need to use the scope resolution operator and no $. Shoe::MY_CONST;
31
How do you get around the issue of $this not working with a static method?
Use self | self::$my_variable;
32
What PHP method can be used to determine if a value exists as a key in an array?
array_key_exists($key, $array)
33
What is an autoload function?
It is a PHP function that attempts to automatically load class files for inclusion. ``` function __autoload($class_name) { include 'class.' . $class_name . '.inc'; } ```
34
How many classes can php extend at the same time?
Only one
35
How do you declare a child class in PHP?
class ClassChild extends ClassParent {}
36
How do you prevent a class from being instantiated?
Declare it as abstract
37
If a class has an abstract method, the class must be...
abstract
38
If an abstract class has a method...
the extending class MUST declare it
39
How do you declare an abstract class?
abstract class myClass { }
40
How do you handle scope when implementing an abstract method in a child class?
You must have the same OR less restrictive scope.
41
Do interfaces have methods?
No
42
Can you use autoloading with interfaces?
Yes
43
How many interfaces can a PHP class implement?
As many as required
44
How do you prevent a method from being overridden in subsequent classes?
Use the final keyword final function myFunc() {...}
45
Can I change the visibility scope when overriding a method?
Yes, but you can't make it stricter
46
Can I redeclare a method (override) that is in an interface?
No
47
How many arguments can an overriding method have?
It must have the same number as the method being overridden (with exception to the __construct method where you can have more or less)
48
How do you copy an object?
Use the clone operator | $obj = clone $myobject;
49
How do you test that two objects are the same type and have the same contents?
Use the == operator
50
How do you test that two objects are the same object?
Use the === operator
51
What is one problem with using the clone operator?
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
52
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)?
Use the __clone magic method
53
What is a reference in PHP?
It's similar to a pointer in c
54
What does the function get_class do?
Returns the name of a class of an object
55
How do you determine if an object is an instance of a particular class?
$object instanceof MyClass
56
How do you assign an object reference to a variable?
$myvar = &$myobject;
57
If I convert an array to an object using typecasting, what is the result?
An object with elements named after the key / value pairs.
58
If I convert a string to an object using typecasting, what is the result?
An object with a single value called scalar containing the string. (i..e var_dump((object) "yo");
59
What parameter to an exception is the error code?
``` The second throw new Exception("message", 1000); ```
60
What is lazy initialisation?
``` 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. ```
61
What is a factory method pattern?
Creates an object without ever naming the class.
62
If you have an array which contains elements which use keys - what sort function should you use?
uasort
63
What is the difference between uasort and usort?
uasort maintains the original keys in the array, whereas usort assigns new keys to each element as it's reordered.
64
What does the list function do?
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.
65
Write a filter expression that tests for a variable being an int and greater than one:
filter_var($_POST['id'], FILTER_VALIDATE_INT, array('min_range' => 1));
66
Taking an input called $_POST['value'], how would you prevent cross site scripting?
strip_tags($_POST['value']);
67
How do you refer to a class 'Foobar', that is in the namespace 'Hello'?
new Hello\Foobar();
68
Making reference to the namespace and calling Hello/Foobar each time is cumbersome - how can we remove this requirement?
use Hello\Foobar as Foobar;
69
How do you register a class / method to perform autoloading functions?
``` spl_autoload_register('autloader', 'autoload'); or spl_autoload_register(__NAMESPACE__ . '\foo::test'); ```
70
Is "require" a statement or a function?
Statement. It is therefore preferable to not use brackets when calling require. I.e. require 'foo'; NOT require('foo');
71
How do you specify which error handler is used by PHP?
set_error_handler('name_of_error_handler');
72
What function allows me to print a backtrace?
debug_print_backtrace()
73
How and why would you change the save location for session data?
Security reasons. You can change it by calling: session_save_path('mypath'); before every call to session_start();
74
In making a singleton - how would you prevent duplication of a class?
Make an empty magic method __clone()
75
When using .htaccess to RewriteRule, how do you make sure variables can be sent in PHP via the URL?
make sure the rule has [QSA] added to the end (Query String Append).
76
What is the difference between ' and " when using variables in PHP?
A variable $var will be treated as literal between two '''s and therefore print $var. However, between two ""'s the variable is evaluated.
77
Why use { }'s with variables in strings?
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']} ";
78
What is the name of the pattern where all requests are routed through a single index.php file?
front controller pattern
79
What is one reason the function session_set_save_handler() would not work?
The php configuration is set to "session.auto_start"
80
When using fwrite, what mode must the file be opened in (assuming system that differentiates between ascii and binary mode files)?
b or binary mode
81
How would you make the first letter in a word / sentence uppercase?
ucfirst(strtolower($string));
82
What is wrong with the following PHP code? ``` class MyClass { public $var1 = get_date(); } ```
It is not possible to set an attribute in a PHP class using an expression, it must be a literal value.
83
What class name can you NOT use due to it already being in use by PHP?
stdClass
84
How do you delete an object once you are finished with it?
unset($object);
85
Are class names case sensitive in PHP?
No (but object names obviously are, as they are variables).
86
``` What is wrong with the following? class MyClass { public $var; function do() { print $var; } } ```
$var is not accessible in that method - you need to use... | $this->var;
87
If PHP can't find a constructor called __construct, what will it look for next?
A constructor with the same name as the class.
88
How do you create a destructor in PHP?
``` function __destruct() { } ```
89
When is a destrutor called on an object?
When it is destroyed (i.e. use unset($obj);)
90
Can a destructor take arguments?
No
91
What is the purpose of the __autoload special function?
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.
92
Is __autoload part of a class definition?
No - it's typically placed in the script where the classes are to be instantiated.
93
What is the phpdoc syntax for a var tag?
@var type
94
What is the phpdoc syntax for a parameter tag?
@param, and @return
95
What is pear?
PHP Extension and Application Repository
96
How would you get phpdoc to document an entire project?
phpdoc -d . -t docs
97
Is the destructor of a parent class automatically called when a child object is destroyed?
No - (unlike some other OO languages)
98
When overriding a method in a child class, what must the signature of the method be?
The same as the parent that you are overriding
99
Protected methods / variables are available to who?
This class and derived classes
100
Can you directly access a protected member via an object?
no
101
How do you refer to a variable / method in a parent class?
parent::doThis();
102
Why should you use static:: over self::
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).
103
When should you use self::
When you want to refer to a method within that class
104
Class constants are like static variables in what way?
They are available across all instances of a class
105
Can a class constant be modified?
No
106
Can a class constant's value be based on another variable?
No
107
Can you access a class constant through the object?
No - it must be accessed through the class classname::attribute;
108
Can a static variable be accessed within a class using $this?
No, you must use self:: or static::
109
How do you call a static variable within the class?
self: :$var; static: :$var;
110
What is different about accessing a static attribute vs static method via an object?
A static attribute cannot be accessed via an object (but a static method can be).
111
How would you call the parent destructor or constructor from a PHP class?
parent: :__construct() parent: :__destruct();
112
What type of functions is $this not available in?
static
113
Does a class with an abstract method in PHP have to be declared as abstract?
Yes
114
What feature must all methods in an interface have?
They must all be public.
115
What PHP function can be used to create a unique user ID?
uniqid(); | Keep in mind it's not truly random, so security is a concern
116
What is on distinction between an interface and a class (regarding inheritence)?
A class can implement multiple interfaces, while a class can only extend a single parent class
117
What kind of copy does the clone operator do in PHP?
By default it's a shallow copy - to customise this use the __clone magic function
118
What do traits allow?
Provides functionality to a class, as if it had inherited from multiple parents.
119
Can you instantiate a trait?
No (like interfaces and abstract classes)
120
How do you create a trait?
``` trait tSomeTrait { function doSomething() { } } ```
121
How do you add a trait to a class?
Use the "use" keyword. ``` class newClass { use tSomeTrait; } ``` newClass now has access to the functions declared within tSomeTrait
122
What function could you use to get a list of methods in a class?
get_object_methods($this);)
123
What function could you use to get a list of variables in a class?
get_object_vars($this);
124
If a trait and a class have a method with the same name, which one takes precedence?
The class method, unless it was inherited from another class - in which case the trait method will take precedence.
125
What is type hinting?
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) { } } ```
126
Does type hinting work with scalar types?
No, only objects
127
Can type hinting be used in functions?
Yes - it doesn't have to be within a class.
128
What can be hinted?
Classes, functions (5.4) interfaces and arrays (5.1)
129
What version of PHP added support for namespaces?
5.3
130
What are the only things that can be stored in a namespace?
Classes, Interfaces, Functions and Constants.
131
Namespaced code should live in it's own...
file
132
In a namespaced file, what is the first thing that should appear in the file?
namespace NameofYourNamespace; (NOTE: HTML must not come before the namespace declaration). (2nd NOTE: namespace can come after the PHP declare() statement)
133
Namespaces can have subnamespaces, how would you organise that?
namespace MyUtilities\UserManagement; class Login { }
134
You have a class called Department in a namespace called MyNamespace - how do you actually reference it? namespace MyNamespace\Department;
$var = new \MyNamespace\Department(); (NOTE the leading slash, which doesn't appear in the declaration).
135
Can the same namespace span multiple files?
Yes
136
What PHP constant represents the current namespace?
__NAMESPACE__
137
What keyword can reduce the amount of typing when dealing with namespaces?
use use MyNamespace\Company;
138
What can you do to prevent a user creating multiple singletons?
Set the access level of the __construct and __clone functions to private
139
Can you test more than one parameter with isset()?
Yes, isset($var1, $var2); will only return true if all parameters are set (it's unlimited number of parameters.
140
What two user defined methods are required for a composite pattern?
Add and Remove
141
What function would you use to find the index of an object in an array?
$index = array_search($e, $array);
142
What is the error surpression operator?
@ i.e. @fopen($file, 'w');
143
Is it appropriate for a constructor to throw an exception if required?
Yes
144
Can a catch block throw an exception?
Yes, and it can be caught by a subsequent catch block
145
What PHP function can be used to determine if a file is writable?
is_writable($file);
146
If you create an extended Exception class, what should it do?
It should call the parent constructor | parent::__construct
147
What is PDO?
PHP Data Object
148
How do you determine what applications are supported by PDO?
print_r(PDO::getAvailableDrivers());
149
How do you create a PDO for MySQL?
$pdo = new PDO('mysql:dbname=test; host=localhost', 'username', 'password'); NOTE the way the dbname and host is passed
150
Once you've finished with a PDO, how do you delete / close the connection?
unset($pdo); or $pdo = NULL;
151
PDO being an object doesn't have errors, but rather throws exceptions - what type of exception?
PDOException try { } catch (PDOException $e) { }
152
What PDO method is typically used to run queries that do not return a result (i.e. INSERT, UPDATE, DELETE)?
$pdo->exec($q);
153
What PDO function can you use to change the error reporting level for your database?
PDO->setAttribute
154
What would you call if, after running a PDO insert, you wanted to know the dynamically generated primary key value?
$id = $pdo->lastInsertId(); | Equiv to mysqli_insert_id()
155
What is the PDO equivalent of mysqli_real_escape_string() to prevent MySQL injection attacks?
$data = $pdo->quote($unsafe_data);
156
Other than preventing sql injection attacks, what else does $pdo->quote() do?
It wraps the data in quotes, meaning you don't have to in the query.
157
What does $pdo->exec() return?
0 if nothing is affected, FALSE if there was an error. A positive number (number of rows affected) if rows are affected.
158
What PDO method do you use to run a query that does return a result?
$result = $pdo->query($q);
159
What does $pdo->query($q) return?
A PDOStatement object
160
How do you determine how many rows where affected after a $pdo->query($q) call?
$results->rowCount() (which is equiv to mysqli_num_rows()
161
I have used a $pdo->query and obtained $results. How do I process these results?
Use PDOStatement::fetch() | $results->fetch()
162
I can't use fetch straight away, I need to tell PHP how to fetch the records, how do I do this?
$pdo->setFetchMode() Pass the options PDO::FETCH_ASSOC PDO::FETCH_NUM PDO::FETCH_OBJ PDO::FETCH_CLASS
163
There is another way to fetch results - without using fetch, how do you do this?
``` foreach($pdo->query($q) as $row) { // Use row } ``` // NOTE Under the hood, it is NOT running the query multiple times
164
Using PDO write a basic query to select username from a table called users.
``` $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
By default, PHP will do what before calling the __construct function of an object when building an object (i.e. PDO::FETCH_CLASS)?
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
What is one benefit of using a prepared statement when dealing with databases?
Because data is sent separately, you don't have to guard against injection attacks (it is handled for you).
167
Write a prepared statement to select everything from a users table given an email address:
$stmt = $pdo->prepare('SELECT * FROM users WHERE email=?');
168
What is the placeholder indicator in a prepared statement?
'?' character represents data to be replaced in the statement.
169
What is the other way (other than using ?) to write a placeholder in a PDO prepared statement?
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
Why are prepared statements so useful?
They have a large performance boost (especially when the same statement is repeatedly called with only the data changing)
171
What version of PHP is the SPL no longer able to be disabled?
5.3
172
What is the SPL?
Standard PHP Library
173
What class (in the SPL) would you use to define your own Session Handling object?
``` SessionHandlerInterface (an interface that defines a set of functions required to handle sessions) class SessionHandler implements SessionHandlerInterface { } ```
174
How would you make PHP use your session handler object?
``` $sh = new SessionHandler(); session_set_save_handler($sh, true); ```
175
What class is useful for getting information about a file?
SplFileInfo($filename); - >getBasename() - >getExtension - >getMTime - >getSize - >getType - >isDir - >isFile - >isWritable
176
If you want to write or change a file, what SPL class can you use to do this?
SplFileObject NOTE: SplFileObject inherits from SplFileInfo - so it has it's functionality too.
177
In procedural PHP you have to close a file stream, when does the stream get closed with an SplFileObject object?
When the object is deleted.
178
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?
The exception classes that are defined in the SPL
179
What SPL interface is useful for creating a method for looping through instances of a class?
Iterator
180
If I have a DirectoryIterator, what iterator can I use with it to limit the types of files that are iterated over?
FilterIterator
181
What SPL class offers better performance (but more limited functionality) when it comes to arrays?
SplFixedArray
182
What SPL class implements a stack data structure?
SplStack
183
What SPL class implements a FIFO data structure?
SplQueue
184
Write a function that autoloads classes as they are required?
``` function class_loader($class) { require ('classes/' . $class . '.php'); } ``` spl_autoload_register('class_loader');
185
What interface would you use on a class if you wanted it to be accessible in much the same way an array is?
ArrayAccess
186
What interface would you use on a class if you wanted to use the count function on it?
Countable
187
What is the syntax for multiple interfaces?
``` class Department implements Iterator, Countable { } ```
188
What is the purpose of serialisation?
To convert complex data into a more digestable format for say, a database to store.
189
An array may have in it's serialized data something like s:5:"karen", what does this mean?
``` s = string 5 = number of characters "Karen" = the data in the array ```
190
When data has been serialised, how do you convert it back to it's original form?
unserialize($sData);
191
Are a methods methods stored when an object is seralized?
No (but they come back when it is unserialized)
192
What do we have to keep in mind when unserializing data?
You must have access to the class definition that you are unserializing too.
193
When are objects automatically serialized / unserialized?
When storing an object in a session
194
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?
strip_tags()
195
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?
There will be no dateAdded field in the class - to solve this use an alias: DATE_FORMAT(dateAdded, "%e %M %Y") AS dateAdded
196
In MVC the view does what?
All the handling of the data display.
197
Can PHP appear in the View?
Yes - but typically very minimal and only for doing formatting and data extraction stuff.
198
How do you open a connection to another website in PHP?
fopen('http://fuckingwebsite.com/index.php', 'r'); NOTE: only 'r' will work of course
199
What function(s) is used to open a socket connection to a site?
fsockopen or fopen
200
What variable can be used to determine a users IP address (actually the ISP's)?
$_SERVER['REMOTE_ADDR']
201
How do you initiate a cURL session?
$curl = curl_init($url);
202
When developing a service, the PHP script must tell the client what?
What format the data is in
203
How do you tell a client what format the data is in?
header('Content-Type: text/plain'); header('Content-Type: text/xml'); header('Content-Type: application/json');
204
How do you encode data into Json in PHP?
echo json_encode($data);
205
How do you open a file to write compressed data to it?
$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
How do you write to a file, that will be compresed?
gzwrite($fp, 'data'); ``` // later gzclose($fp); ```
207
What two functions can be used to read from a compressed file?
readgzfile() | gzfile()
208
Assuming an empty directory, what is wrong with the following code? mkdir('backup/test', 0777);
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
What library can I use to encrypt data?
mcrypt
210
What function can I use to get a list of supported mcrypt encryption algorithms?
$algos = mcrypt_list_algorithms();
211
What is an IV?
Initialisation Vector - input into a cryptographic primitive.
212
How do you create an IV in PHP?
$m = mcrypt_module_open('rijndael-256', '', 'cbc', ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($m), MCRYPT_DEV_RANDOM);
213
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)?
Use md5 to generate a key from a random string. MD5 always returns a 32 character string. $key = md5('some string');
214
Once you have created your IV - what is the next step mcrypt requires?
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
What function is used to encrypt data once mcrypt is setup?
$encrypted = mcrypt_generic($m, $data);
216
How do you cleanup after using mcrypt?
mcrypt_generic_deinit($m); | mcrypt_module_close($m);
217
What function is used to decrypt data having been encrypted with mcrypt?
$data = mdecrypt_generic($m, $encrypted);
218
What must the same in order to decrypt data?
The key and the IV (initialisation vector)
219
What functions should you use if you have to pass non-hardcoded functions to a system command?
escapeshellarg() or | escapeshellcmd()
220
What is one of getting input back from the command line?
Using backticks (i.e. $var = `ls`; will run ls on the command line and return the results).
221
Which function, like system(command) can return input from the command line but in binary format?
passthru(); | shell_exec(command);
222
What's one reason shell_exec, exec, or system may fail?
The external app being run may require more memory than allowed by PHP.INI (look for memory_limit)
223
How do you run php in a pseudo web server mode from CLI?
php -S localhost:8000 Then connect to it through a web browser "http://localhost:8000/script I want to run"
224
How do you create a new Expat parser for XML?
$p = xml_parser_create();
225
Expat is an .... XML parser?
event based
226
What is the limitation of using Expat?
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
What is a more flexible system for parsing XML?
simplexml
228
What function can you use to get information (size, type) so it can be used in HTML?
getimagesize(nameoffile);
229
How do you load an xml file and parse it using simplexml?
$xml = simplexml_load_file('nameoffile.xml'); | foreach($xml->mynode as $mynode) { // do things }
230
What is the trick with comparing XML data as an XML string?
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
Which of the XML parsers supports XPath?
SimpleXML
232
What is a downside to using DOM parsers (simple XML)?
It uses more information than the SAX parsers on the server, as it stores the entire document in a variable.
233
xdebug can be used to see the superglobals - how does this work?
Use ini_set to configure what you see ini_set('xdebug.dump.SERVER', '*'); xdebug_dump_superglobals();
234
Using PHPUnit, which function can be added to a test class to ensure the 'fixtures' are in place?
setUp() { } And use tearDown() { } to clean up
235
What class does a class extend from to use UnitTesting?
PHPUnit_Framework_TestCase
236
What does the end / prev functions do?
``` Act as iterators on an array $value = end($array); while ($value) { $value = prev($array); } ```
237
What function can be used to walk an array and perform a user defined action on it?
array_walk()
238
What function would you use to get a count of how many times each UNIQUE value occurs in an array?
array_count_values
239
How could you write a conditional statement that ensured the parameter passed was of type MySQLi?
if ($instance instanceof MySLQi) { }
240
If a derived class does not have a constructor, are the parent class constructors automatically called?
Yes. If the child DOES have a constructor, it will have to manually call the parent constructor.
241
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?
``` 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
How do call the constructor for the current class (i.e. to create itself)?
$_instance = new self(); Using self();
243
Static methods cannot access...
properties in a class (just static members)
244
Can an object be assigned to a constant?
No, only primitive types
245
How do you refer to a constant in code?
self: :CONSTANTNAME; or classname: :CONSTANTNAME;
246
What is the one case in which a derived class doesn't have to implement all the methods in an abstract parent class?
When it itself is abstract.
247
How do you use multiple traits in the one class?
One after the other with commas. | trait traitClass1, traitClass2;
248
If a class implements an interface, under what condition does that class not have to directly implement the interface?
If it uses a trait that implements it on the classes behalf.
249
If I have two traits, PriceUtilities and TaxTools, both with a calculateTax method - how could I avoid a method naming conflict?
use PriceTools, TaxTools { TaxTools::calculateTax insteadof PriceUtilities; } Use the insteadof keyword.
250
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?
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
When using the 'as' keyword to alias a method in a trait, what MUST you do as well?
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
What else can the 'as' keyword be used for?
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
How are static methods accessed via a trait?
The usual way - there is no difference
254
Can traits access properties in a host class?
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
Can you change the access level of a trait in a host class?
Yes - using the 'as' operator use PriceUtilities { PriceUtilities::calculateTax as private; ....
256
What would the problem be with moving a create function to the superclass, if it uses the self:: keyword?
self refers to the context of resolution, NOT the calling context. So it would be effectively like parent::create, and not $this::create
257
What does the static() keyword do?
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
What version of PHP did static keyword (for late static binding) come in?
5.3
259
What else can you use static keyword for?
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
What does file_put_contents do?
It writes data to a file, and is equivalent to calling fopen, fwrite and fclose in succession.
261
What function can you use to load XML data?
simplexml_load_file($filename)
262
What function converts a string into XML?
public mixed SimpleXMLElement::asXML($data)
263
Given a SimpleXMLElement, what function could you use to search for one of the XML elements?
SimpleXMLElement::xpath("xpath expression");
264
What does the basename function do?
Returns the trailling name component of path. i.e. bsaename("/etc/sudoers.d", ".d") returns sudoers
265
What is the rule of thumb when using multiple catch clauses?
Use the most specialised first, and generic last - otherwise they will always be caught by the generic exception.
266
When using customised exceptions - it's always a good idea to have one last catch clause to catch what?
Exception objects - as a last ditch barrier to errors.
267
What version of PHP did the finally clause appear in?
5.5
268
How would you prevent a class called 'Checkout' from being inherited from?
final class Checkout { }
269
How would you prevent a method called foobar from being overriden in a subclass?
public final function foobar() { }
270
What is an interceptor method?
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
What function can be used to determine if a method exists in a php object?
method_exists($this, $method)
272
When does the __isset intercept method get called?
When a user uses isset() on a property that doesn't exist.
273
Why would you use __isset in conjunction with __get
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
Why should a class that uses interceptor methods document this fact very clearly?
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
What is delegation?
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
``` class CopyMe{} $first = new CopyMe(); $second = $first; ``` How do these statements differ between PHP 4 and 5?
In 4, $first and $second are two distinct objects. In PHP 5 they refer to the same object.
277
Why is using the clone operator (with __clone intercept method)?
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
Where does the __clone method run, the copied, or original object?
The copied object.
279
How are properties copied in an object when cloning?
primitive objects are shallowed copy, but object properties are copied by reference.
280
How do you solve the issue that an objects property of type object may be copied by reference?
Make sure to implement a __clone intercept method and clone the object properties so that they are each individuals.
281
What function can you use to test if a callback is callable?
is_callable()
282
Why might you want to add callback functionality to your objects?
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
If you wanted to pass a function around via a variable, what is one way to do this via inbuilt php functions?
Use create_method | $logger = create_function('$product', 'print " logging({$product->name})\n";');
284
Creating a function via create_function uses ... functions.
anonymous
285
create_function is one way to create an anonymous function - what is another way (post PHP 5.3)?
$logger = function ($product) { print " logging ({$product->name})\n"; }; // Note the ';' at the end!!!!
286
How would I go about sending an object method to a callback register function (it will be tested by is_callable())?
$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
How can a function be returned from a function (like a function factory)?
``` return function ($product) { if ($product->price > 5) { print "Stuff is expensive now... {$product->price}\n"; } } ```
288
What is a closure?
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
How do you implement a closure in PHP?
``` 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
``` What is the difference between: file1.php namespace main; com\utils\Debug::helloWorld(); file2.php namespace main; \com\utils\Debug::helloWorld();; ```
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
``` 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; ```
util\Debug::myMethod();
292
``` 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; ```
Debug::myMethod();
293
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?
use com\utils\Debug as uDebug; | Now I can use the alias, uDebug.
294
If I have an object called "Lister" in the local namespace, and I also have one in the global namespace, how do I differentiate?
Lister::myMethod(); // Calls local version | \Lister::myMethod(); // Calls global version
295
Is it possible to have multiple namespaces in a single file/
Yes - make sure you use the braces - and you can't use a mix of the line / braces syntax in the same file.
296
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?
Use the include_path value in php.ini to specify the folder where PHP can find them.
297
How can you set the include path programatically?
set_include_path( get_include_path() . PATH_SEPARATOR . "/home/mycoolproj/phplib/");
298
``` You can use a string to instantiate a class name. How would you do that given: $classname = "foobar"; ```
$newObj = new $classname();
299
What function can you use to get a list of all classes defined in a script process?
get_declared_classes();
300
Why would you use the ::class operator?
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
How do I obtain a list of all the methods on a class?
get_class_methods("class");
302
How could I test whether a method exists in a class using in_array?
if (in_array($method, get_class_methods($obj))) { | }
303
What is the best way to determine if a method name is valid?
if (is_callabel(array($product, $method)) { $product->$method(); // Note the $ in front of method }
304
What is the equivalent function to get_class_methods() for getting a list of properties from an object?
get_class_vars("classname"); NOTE: Like get_class_methods - it requires the name of a class passed as a string
305
How would you find out the name of a parent class?
get_parent_class('classname');
306
What is the opposite of get_parent_class() (i.e. subclass)?
is_subclass_of($object, 'classname'); // Returns true if $object is a subclass of classname
307
Can is_subclass_of be used to determine if a class implements an interface? If Not, what should be used?
No it doesn't - you should use instanceof operator.
308
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?
call_user_func(array($obj, "myFunc")); // or if you have defined a variable to hold "myFunc" call_user_func(array($obj, $method));
309
If you have a variable number of arguments, how could you use call_user_func?
Don't - use call_user_func_array. | call_user_func_array(array($obj, $method), $args); // Where $args is an array of arguments.
310
What class is useful for determining information about a class?
ReflectionClass ReflectionMethod etc.
311
How would you use reflection to get information regarding a class/
``` $foobar_class = new ReflectionClass('foobar'); Reflection::export($foobar_class); ```
312
ReflectionClass has a number of useful functions for determining information about a class, name some.
ReflectionClass::getName(); ReflectionClass::isUserDefined(); ReflectionClass::isAbstract(); ReflectionClass::isInterface();
313
What is the caveat with ReflectionMethod::returnsReference()?
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
How do you get the class that refers to a methods parameters?
ReflectionMethod::getParameters(); which returns a ReflectionParameters object.
315
What is one sign that the code design requires more polymorphism?
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
What's one way to prevent performance issues when using reflection?
Cache the results if you know the values wont change (for instance when creating a pseudo enum class which contains fixed constants).
317
What is one strategy to create configuration settings for your applications?
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
What does a composite pattern seek to do?
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
What does the array_udiff function do?
Computes the difference between two arrays by using a callback function.
320
What is the one issue with the composite pattern with regards to composites and leaves sharing the same interface?
The leaves must also implement the addUnit and removeUnit methods even though they are not aggregators.
321
If a class inherits from an abstract class, and does not define a constructor itself - does the sibling inherit the parents constructor?
Yes, and the appropriate parameters must be passed.
322
``` The following code is an example of... function getWealthFactor() { return $this->tile->getWealthFactor(); } ```
Delegation
323
What built in objects are used to facilitate the Observer pattern in PHP?
SplObserver (maps to what I would consider Observer) | SplSubject (maps to what I would consider Observable)
324
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?
$storage = new SplObjectStorage();
325
What does clearstatcache do?
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
What does filemtime() do?
Gets the file modification time
327
If you are serializing objects, not everything can serialize, give an example?
Resources, such as database connections - you have to destroy the connection and re-establish it when you create the unserialized object
328
What two magic methods are useful for serialisation of objects that have resources attached?
__wake and __sleep. You can for instance shutdown a database connection in the sleep - and re-establish it in the __wakeup
329
What filter (using filter_var) can be used to clean up a URL?
filter_var($url, FILTER_SANITIZE_URL);
330
Is '=& $variable' and '= &$variable' the same thing?
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
Does executable code in a file that is included, get executed?
Yes
332
What kind of arrays cannot be directly converted into JSON?
Pure arrays, i.e. ordered, numerical index
333
What is the only data type that cannot be converted using JSON?
A resource type
334
What happens with private variables in an object when passing to json_encode?
They are ignored, only public variables get converted to JSON
335
What method would you write to serialize an object to json (and preserve private vars)?
``` Write a public method called JsonSerialize (and implement the JsonSerializable interface): public function JsonSerialize() { $vars = get_object_vars($this); return $vars; } ```
336
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?
``` 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
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?
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
What is the risk of not catch exceptions correctly with PDO?
You could expose your password to the database.