PHP Flashcards
Define a query for MySQL using PHP?
mysqli_query($connection, $query);
(Query can be an insert, delete etc…
What function can we use for preventing SQL injection attacks on user input?
mysqli_real_escape_string($db, $string);
Old school way…
addslashes($string);
What function do we use to find out what the last connection error was in mysql?
mysqli_connect_error();
mysqli_connect_errno();
What function connects to a database?
mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
What function to you use to determine what error occurred when performing database queries?
mysqli_error($connection);
What function do you use to close a connection with a mysql database?
mysqli_close($connection);
Given a query that returns a number of results, how to you iterate through the results?
$result = mysqli_query($connection, $query);
while ($subject = mysqli_fetch_assoc($result)) { // output the results }
What mysqli api will give you the count of a set?
mysqli_num_rows($set)
This can be useful for determining how many “of a thing” you have
What kind of redirect does header() perform?
302 Redirect
How do you redirect to a page, say “login.php”?
header(“Location: login.php”);
exit;
NOTE: That you don’t need the 302 status code
What does a 302 status in the header do?
It tells the browser to do a second get request to the new location.
Why does session_start have to come at the start of a page?
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 would you print the current year in php?
echo date(“Y”);
How would you print the current year in php?
echo date(“Y”);
How would you include a class definition file?
require ‘class.Definition.inc’;
How do you instantiate a class?
$newclass = new Class; $newclass = new Class(); // Both seem to call the constructor
How do you unset a variable that has already been set?
unset($variable_name);
What is a magic method?
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)
When is __set(string $name, mixed $value) called?
When an inaccessible member is referenced (attempted to write to)
When is __get($name) called?
When an inaccessible value is read from
What is the equivalent of a constructor in PHP?
__construct()
If you have a variable name stored in a variable. How do you access the variable that the name refers to (in a class)?
$this->$name
note the use of $ after the ->
What is the best way to setup a __construct method if you expect to populate it from a database.
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;
}
What magic method would you use to allow an object be printed as a string?
__toString()
var_export is similar to var_dump, but how is it different?
It returns valid PHP code whereas var_dump does not.
What is the scope resolution operator in PHP?
:: - same as C++
How would you access a static variable named ‘foobar’ in a class named ‘Shoe’?
Shoe::$foobar;
What is the best practise for naming constants in PHP?
Uppercase with underscores. MY_CONST
How do you declare a constant variable in a class in PHP?
const ADDRESS_TYPE = 1;
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;
How do you get around the issue of $this not working with a static method?
Use self
self::$my_variable;
What PHP method can be used to determine if a value exists as a key in an array?
array_key_exists($key, $array)
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'; }
How many classes can php extend at the same time?
Only one
How do you declare a child class in PHP?
class ClassChild extends ClassParent {}
How do you prevent a class from being instantiated?
Declare it as abstract
If a class has an abstract method, the class must be…
abstract
If an abstract class has a method…
the extending class MUST declare it
How do you declare an abstract class?
abstract class myClass { }
How do you handle scope when implementing an abstract method in a child class?
You must have the same OR less restrictive scope.
Do interfaces have methods?
No
Can you use autoloading with interfaces?
Yes
How many interfaces can a PHP class implement?
As many as required
How do you prevent a method from being overridden in subsequent classes?
Use the final keyword
final function myFunc() {…}
Can I change the visibility scope when overriding a method?
Yes, but you can’t make it stricter
Can I redeclare a method (override) that is in an interface?
No
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)
How do you copy an object?
Use the clone operator
$obj = clone $myobject;
How do you test that two objects are the same type and have the same contents?
Use the == operator
How do you test that two objects are the same object?
Use the === operator
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
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
What is a reference in PHP?
It’s similar to a pointer in c
What does the function get_class do?
Returns the name of a class of an object
How do you determine if an object is an instance of a particular class?
$object instanceof MyClass
How do you assign an object reference to a variable?
$myvar = &$myobject;
If I convert an array to an object using typecasting, what is the result?
An object with elements named after the key / value pairs.
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”);
What parameter to an exception is the error code?
The second throw new Exception("message", 1000);
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.
What is a factory method pattern?
Creates an object without ever naming the class.
If you have an array which contains elements which use keys - what sort function should you use?
uasort
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.
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.
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));
Taking an input called $_POST[‘value’], how would you prevent cross site scripting?
strip_tags($_POST[‘value’]);
How do you refer to a class ‘Foobar’, that is in the namespace ‘Hello’?
new Hello\Foobar();
Making reference to the namespace and calling Hello/Foobar each time is cumbersome - how can we remove this requirement?
use Hello\Foobar as Foobar;
How do you register a class / method to perform autoloading functions?
spl_autoload_register('autloader', 'autoload'); or spl_autoload_register(\_\_NAMESPACE\_\_ . '\foo::test');
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’);
How do you specify which error handler is used by PHP?
set_error_handler(‘name_of_error_handler’);
What function allows me to print a backtrace?
debug_print_backtrace()
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();
In making a singleton - how would you prevent duplication of a class?
Make an empty magic method __clone()
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).
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.
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’]} “;
What is the name of the pattern where all requests are routed through a single index.php file?
front controller pattern
What is one reason the function session_set_save_handler() would not work?
The php configuration is set to “session.auto_start”
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
How would you make the first letter in a word / sentence uppercase?
ucfirst(strtolower($string));
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.
What class name can you NOT use due to it already being in use by PHP?
stdClass
How do you delete an object once you are finished with it?
unset($object);
Are class names case sensitive in PHP?
No (but object names obviously are, as they are variables).
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;
If PHP can’t find a constructor called __construct, what will it look for next?
A constructor with the same name as the class.
How do you create a destructor in PHP?
function \_\_destruct() { }
When is a destrutor called on an object?
When it is destroyed (i.e. use unset($obj);)
Can a destructor take arguments?
No
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.
Is __autoload part of a class definition?
No - it’s typically placed in the script where the classes are to be instantiated.
What is the phpdoc syntax for a var tag?
@var type
What is the phpdoc syntax for a parameter tag?
@param, and @return
What is pear?
PHP Extension and Application Repository
How would you get phpdoc to document an entire project?
phpdoc -d . -t docs
Is the destructor of a parent class automatically called when a child object is destroyed?
No - (unlike some other OO languages)
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
Protected methods / variables are available to who?
This class and derived classes
Can you directly access a protected member via an object?
no
How do you refer to a variable / method in a parent class?
parent::doThis();
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).
When should you use self::
When you want to refer to a method within that class
Class constants are like static variables in what way?
They are available across all instances of a class
Can a class constant be modified?
No
Can a class constant’s value be based on another variable?
No
Can you access a class constant through the object?
No - it must be accessed through the class
classname::attribute;
Can a static variable be accessed within a class using $this?
No, you must use self:: or static::
How do you call a static variable within the class?
self: :$var;
static: :$var;
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).
How would you call the parent destructor or constructor from a PHP class?
parent: :__construct()
parent: :__destruct();
What type of functions is $this not available in?
static
Does a class with an abstract method in PHP have to be declared as abstract?
Yes
What feature must all methods in an interface have?
They must all be public.
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
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
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
What do traits allow?
Provides functionality to a class, as if it had inherited from multiple parents.
Can you instantiate a trait?
No (like interfaces and abstract classes)
How do you create a trait?
trait tSomeTrait { function doSomething() { } }
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
What function could you use to get a list of methods in a class?
get_object_methods($this);)
What function could you use to get a list of variables in a class?
get_object_vars($this);
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.
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) { } }
Does type hinting work with scalar types?
No, only objects
Can type hinting be used in functions?
Yes - it doesn’t have to be within a class.
What can be hinted?
Classes, functions (5.4) interfaces and arrays (5.1)
What version of PHP added support for namespaces?
5.3
What are the only things that can be stored in a namespace?
Classes, Interfaces, Functions and Constants.
Namespaced code should live in it’s own…
file
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)
Namespaces can have subnamespaces, how would you organise that?
namespace MyUtilities\UserManagement;
class Login { }
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).
Can the same namespace span multiple files?
Yes