Category Archives: PHP

Serializing Objects

o Functions: serialize() / unserialize()

o Magic method __sleep() is executed with serialization, if available o allows you to specify which properties should be stored (serialized) and which should not be stored

o Can also create/change properties for serialization

o Magic method __wakeup() is executed with deserialization, if available ex: to open a database connection unique to the object

Share

__clone()

Object cloning is creating a copy of an object. An object copy is created by using the clone keyword and the __clone() method cannot be called directly. In PHP, cloning an object is doing a shallow copy and not a deep copy. Meaning, the contained objects of the copied objects are not copied. If you wish for a deep copy, then you need to define the __clone() method.

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.

<?php
 class Customer {
 private $name;
 
 public function setName($name) {
 $this->name = $name;
 }
 
 public function getName() {
 return $this->name;
 }
 
 public function __clone() {
 $c = new Customer();
 $c->setName($this->name);
 return $c;
 }
 
 }
 
 $c1 = new Customer();
 $c1->setName("phpcode");
 
 $c2 = clone $c1;

$c2->setName("phpcodez");
 
 echo $c1->getName()."\n";
 echo $c2->getName()."\n";
?>
Share

Cookies

Way of storing data in a browser to id / track a user . Create (set) cookies with the setcookie() or setrawcookie() function and It must be called before sending any output to browser .

It can delay script output using output buffering, to allow time to decide to set cookies or send headers

Setcookie() params are defined according to specifications:

  • $name=value string
  • $value=value string
  • $expire=date optional; default is session end
  • $path=path specifies urls in a domain for which cookie is valid
  • $domain=domain_name check on domain attributes of cookies against host internet domain name
  • $secure cookie only transmitted via secure channels (https); boolean
  • $httponly cookie only made accessible via http protocol, not javascript; boolean

Access with $_cookie or $_request superglobals . Cookie data from the client is automatically sent to $_cookie, if params of variables_order() include “c” (environment/get/post/cookie/server) . It will overwrite itself if name, path, domain, secure, and http_only are identical .

Cookies are part of the http header o as with sessions, multiple values can be assigned to an array and To assign all values to only one cookie, can use serialize() or implode() with first value

Share

Form

Way of collecting data online from user accessing a web site.

Form data automatically available to php scripts. Dots and spaces in variable names converted to underscores.

Form data can be made into an array using the following syntax <input name=”FormArray[]”> .

Group elements by assigning the same array name to different elements; can specify keys.

$_POST superglobal contains all POST data; paired with post method

$_GET superglobal contains all GET data and $_REQUEST is independent of data source, and merges information from sources like GET, POST, and COOKIES; usage is not recommended

Share

Sessions

Way of preserving data across a series of web site accesses by the user . session support is enabled by default . configuration options set in php.ini .SID(STRING) is a pre-defined constant within this extension.

User assigned a unique identifier, the “SESSION ID”. Session id is stored in a cookie on the client or in the url .

Site access by user triggers session id check automatically session.auto_start = 1 or upon request … using session_start().

$_SESSION is available as a global variable.

Enable session.use_only_cookies to enforce cookie usage (and prevent session ids in the url) and enable session.cookie_httponly to prevent javascript cookie access (and help prevent session hijacking via xss) .

Share

Finally

Finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

<?php
 function doSomething($a, $b) {
 return $a / $b;
 }
 
 try {
 doSomething(1);
 } catch (Exception $ex) {
 echo 1;
 } catch (ArgumentCountError $ace) {
 echo 2;
 } catch (DivisionByZeroError $dbze) {
 echo 3;
 }finally {
 print "This part is always executed\n";
 }
?>
Share

__invoke

PHP does not allow the passing of function pointers like other languages. Functions are not first class in PHP. Functions being first class mainly means that you can save a function to a variable, and pass it around and execute it at any time.

The __invoke method is a way that PHP can accommodate pseudo-first-class functions.

The __invoke method can be used to pass a class that can act as a closure or a continuation, or simply as a function that you can pass around.

The __invoke() method is called when a script tries to call an object as a function.

<?php
 class Invoke {
 public function __invoke($x)
 {
 var_dump($x);
 }
 }
 $obj = new Invoke;
 $obj(5);
?>
Share

Generator

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

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.

Once there are no more values to be yielded, then the generator function can simply exit, and the calling code continues just as if an array has run out of values.

• A mechanism to generate iterators

• A generator function returns multiple values

• Individual values are returned using the yield keyword

• Generator may use return for the final return expression; the generator´s getreturn() method gives access to this value.

function myGenerator() {
for ($i = 1; $i <= 10; $i++) {
yield $i;
}
}

Share