PHP Topics | Latest Features | Lesser known Facts | Important for Entrance Exams

PHP Topics | Latest Features | Lesser known Facts | Important for Entrance Exams In this post, I am going to add my other personal projects that I have worked on in various technologies

Reflection in PHP5

$class = new \ReflectionClass(MyClass’);
$method = new \ReflectionMethod('MyClass',’method’);
$args = array();
$method->invoke($method->getDeclaringClass()->newInstanceArgs($args));

Traits in PHP

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance. Avoids the problems of Multiple inheritance.

Is a parent constructor called implicitly in PHP?

When a constructor is defined for a class in PHP, the parent constructor is not called. When no constructor is defined and the parent constructor is not private, it is called implicitly.

Object cloning in PHP

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Object iteration in PHP

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Object Iteration through Implementing Iterator Interface.

<?php class MyIterator implements Iterator { private $var = array(); public function __construct($array){ if (is_array($array)) { $this->var = $array; } } public function rewind(){ echo "rewinding\n"; reset($this->var); } public function current(){ $var = current($this->var); echo "current: $var\n"; return $var; } public function key() { $var = key($this->var); echo "key: $var\n"; return $var; } public function next() { $var = next($this->var); echo "next: $var\n"; return $var; } public function valid(){ $key = key($this->var); $var = ($key !== NULL && $key !== FALSE); echo "valid: $var\n"; return $var; } } $values = array(1,2,3); $it = new MyIterator($values); foreach ($it as $a => $b) { print "$a: $b\n"; } ?>

Generators in PHP

A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.

When a generator function is called, it returns an object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.

Type hinting in PHP

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated To specify a type declaration, the type name should be added before the parameter name.

Autoloading files in PHP

Using autoloading, you can load many files in one function without having to write a long list of needed includes at the beginning of each script You may define an spl_autoload_register function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

Object Serialization in PHP

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP.unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.

What is $_SERVER in PHP?

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

What is & operator in PHP?

It is unary operator which gets the reference of a variable it operates on

How to redirect to a URL in PHP?

$url = 'http://www.example.com/';
header('Location: '. $url);

How to use variables defined in outer class in closures?

$var = 'test';
self::func('key',function() use ($var){
});

Calling the same function with variable number of arguments:

Use get_func_args() in the function to get array of arguments.

function demo() {
$args = get_func_args();
for($i=0;$i<get_num_args();$i++) {
	//do some processing with each argument
}
}

How to change value of ini variables in PHP?

ini_set(‘variable_name’,’variable_value’);

Output Buffering in PHP

ob_start() will turn output buffering on. While output buffering is ON no output is sent from the script (but headers), instead the output is stored in an internal buffer. to get contents from output buffer we can use ob_get_contents function
This function will redirect the output to a buffer. We can flush out the buffer ob_end_flush().

list() in PHP

list — Assign variables as if they were an array
<?php
$result = $pdo->query("SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = $result->fetch(PDO::FETCH_NUM)) {
    echo " \n" .
          "  $name\n" .
          "  $salary\n" .
          " \n";
}

?>

Anonymous Classes in PHP7:


<?php
// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

Late Static Bindings

Late static bindings which can be used to reference the called class in a context of static inheritance Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined.

Executing a function name as a string:

$funcName = ‘testFunction’;
$args = array();
call_user_func_array($funcName,$args);

Deleting a file:

unlink($filePath);

File Pattern Matching:

Using glob(): Returns an array of all files in the directory pointed by $fileDir;

$filesList = glob($fileDir . ‘/*’ );

Browser Information:

Using get_browser(null,true); will return an array containing all the useful information for an User Agent header

Comments

Popular posts from this blog

XPath for HTML markup

Apache Hadoop | Running MapReduce Jobs

Laravel | PHP | Basics | Part 2