Php 7 Cheat Sheet



Codemy.com 1 PHP CHEAT SHEET CODEMY.com Basic PHP Structure: php // This is a comment echo 'This is my first php file!' This PHP cheat sheet collection is inspired by the Blueshoes cheat sheet and licensed under the GPLv3 software license. You can view and fork the source on GitHub. Pull requests welcome. PHP Cheat Sheet Fast, flexible and pragmatic scripting language. ##### TABLE OF CONTENTS PHP Basics 3 Variables and Constants 3 PHP Arrays – Grouped Values 8 PHP Strings 13 PHP Operators 20 Loops in PHP 22 Conditional Statements 23 Working with Forms in PHP 24 PHP Filters 25.

PHP supports OOPS programming paradigm which bundles data (properties) and related functions (methods) in independent units called objects.

Php 7 cheat sheet printablePhp 7 Cheat Sheet
Features/SyntaxDescription/examples

class

A class is a blueprint from which we create object instances. A class mainly contains properties and methods.

Variables and functions are called properties and methods respectively in OOP world.

'new' keyword

To create an instance of a class, new keyword is used new MyClass();

pseudo-variable $this

The reference to the current object, only used within the class.

Object operator ->

Used when calling a method or accessing a property on an object instance. It is used with $this as well.

Output:

Visibility

The visibility keywords (public, protected, private) determines how an object properties/methods are accessible:

  • public: can be accessed anywhere.
  • protected: can be accessed by the class and subclasses only.
  • private: can be accessed by the class only.

A property must be defined with one of the above visibility keywords.

A method defined without any of them will have public visibility by default.

Output:

Class constants

Just like defining other constants (outside of a class) using 'const' keyword, we can also define them inside a class. The default visibility of class constants is public.

Constants are allocated once per class, and not for each class instance.

Scope Resolution Operator (::)

Instead of using ->, double colon allows access to static and constant. This operator is also used to access super class features.

Using 'self'

Instead of using $this, the self keyword is used to access constants within the class. Generally, for all class level access self should be used and for all current object instance access $this should be used within the class.
Output:

static properties and methods

Class properties and methods can be declared with static keyword which makes them class level features and we don't need a class instance to access those features.

Like class constants we access static properties/methods with double colon (::) and to access them within class we use self keyword.

$this is not available inside a static method.

By default static features have 'public' accessibility.

For static variable initialization, the same rules apply as const expressions.

Output:

Constructors and destructors

A constructor function __construct() is a special (magic) function which is automatically called when an object instance is created with 'new' keyword. A constructor can have any number of user defined parameters. Constructors should ideally be used to initialize object

A destructor is a special function __destruct() which is automatically called when object is deleted from memory by garbage collector.

Objects are deleted as soon as no references of them used in the program, or during the shutdown sequence.

Destructors are typically used for cleanup, state persistence, etc.

Output

Inheritance:

Inheritance is the process of extending an existing class (parent class) by a new class (subclass) using extends keywords.

A subclass inherits all properties and methods from it's super (parent) class except for private ones.

Inheritance is used for code reuse and polymorphism.

PHP allows single inheritance (at most one super class)

Output:

Inheritance and Construct/destruct

Parent class constructor/destructor are not implicitly called if the child class defines them as well. In order to run a parent constructor (or destructor), a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method.

parent keyword

Similar to 'self' keyword which is used to access class level static and constant features, parent is used to access super class level features from subclass that includes construct/destruct and overridden methods (next topic).

Output:

Method overriding

Method overriding is the process where a subclass redefine a parent class method to change it's behavior. The signature should exactly be the same.


In case if we want to access parent level features from within a subclass then we will use parent::

Output

Abstract classes

An abstract class cannot be instantiated. They provide base class abstract implementation to be extended to provide some specific behavior.

An abstract thing doesn't exist in reality e.g. an animal doesn't exists as a concrete thing but an specialization e.g. dog does exist.

An abstract class definition starts with abstract keyword.

An abstract class can defined method(s) without body. In that case, we have to use abstract keyword in the method signature.

A subclass must override abstract methods or otherwise should be 'abstract' themselves.

Output:

Interfaces

Like an abstract class, Interface is another way to define abstract type.

Interfaces define methods without implementation. They don't have to use abstract keyword.

To define an interface we use interface keyword instead of class.

All methods in an interface should be public.

Class implementing interfaces

A class may implement one or more comma separated interfaces by using implements keyword. The class must implement all interface methods or otherwise should be declared abstract.


Interfaces can extend each other by using keyword extends

Output:

Traits

A Trait is intended to reduce some limitations of PHP single inheritance model. A developer can reuse sets of methods freely in several independent classes living in different class hierarchies..

  1. A trait is defined using keyword trait. It is similar to a class, but cannot be instantiated it's own.
  2. A trait can have properties and magic methods. It can also have static properties and methods.
  3. To use them in a class use keyword use followed by the trait name. A class can have multiple comma separated traits.
  4. In case of conflicts, the class overrides trait functions, but if those functions are defined in a parent class of the current class then traits overrides them.
  5. If two traits have a method with the same name, a fatal error is produced. We can resolve the conflict by using insteadof operator:
  6. Since insteadof operator excludes one of the method, we can re-include the excluded method by using as operator which gives an alias to the method.
  7. We can also change the visibility of a method using as operator:
  8. A trait can use other traits too:
  9. A trait can have abstract methods too. In that case classes using them have to implement the method.
Output:

Final keyword

A method declared with final keyword cannot be overridden by a subclass.

A class declared with final keyword cannot be extended.

Output: Output:

Objects equality

  • The comparison operator compares the objects by their property values and by types. Two objects are equal if they are instances of the same class and have same property values and, even though they are different references.
  • The identity operator compares the object by their references. The object variables are identical if and only if they refer to the same instance of the same class.
Output:

Object iteration

By default all visible properties can be iterated using foreach loop.

To control iteration process we can implement built-in Iterator interface.

Output:

Auto-loading Classes

For a typical PHP application, a developer has to use multiple include statements to include multiple files. Per good practice, there should be a single class in a file.

spl_autoload_register function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

Assume class A resides in A.php and class B resides in B.php at the same location as this Test.php script:

Magic methods

These special methods get called in response to a particular event or scenario. We just have to implement them in our class. These methods starts with double underscores. We have seen two magic methods above already: __construct() and __destruct().

Here's the complete list: __construct(), __destruct()__toString(), __set(), __get(), __isset(), __unset(), __call(), __callStatic()__invoke(), __set_state(), __clone(), __sleep(), __wakeup(), and __debugInfo()

we are going to explore them in the following sections.

String representation of objects

__toString()

This method should return a string. It's a way to represent an object as a string.

Output:

Property Overloading

__set(), __get(), __isset(), __unset()

This is a way to dynamically create object properties which do not exist or are inaccessible.

  • __set(): is triggered when an inaccessible property is assigned a value.
  • __get(): is triggered when an inaccessible property is accessed.
  • __isset(): is triggered when calling built-in functions isset() or empty() on inaccessible properties..
  • __unset(): is triggered when calling built-in function unset() on inaccessible properties.
Output:

Method overloading

__call(), __callStatic

This is a way to dynamically create object methods which do not exist or are inaccessible.

  • __call(): is triggered when calling an inaccessible method of an object.
  • _callStatic(): is triggered when calling an inaccessible static method methods of a class.
Output:

Calling object as a function

__invoke() method is triggered when a script tries to call the target object as an function.

It can be used to pass a class instance that can act as a closure, or simply as a function that we can pass around, and can invoke it without knowing if it's an object or without knowing what object it is.

Output:

Object Cloning

__clone() method of a newly cloned object is triggered just after it has been cloned by using clone keyword.

__clone() method allows any necessary properties that need to be changed after cloning.

When an object is cloned by using clone keyword, PHP performs a shallow copy of all of the object's properties. Any properties that are internal object references will not be cloned and will remain references. Using __clone(), we can explicitly cloned internal objects too. There can be an recursive _clone() method calls to achieve deep cloning.

Output:

removing __clone() method of MyClass will give output of TRUE, confirming that two $var are still pointing to same reference.

Serialization

__sleep() and __wakeup()

__sleep() method triggered when serialize() function is invoke on the target object.

serialize generates a storable string representation of a value.

To deserialize string to PHP type we use unserialize() function. In that case the magic method __wakeup() is invoked on the target object.

The purpose of these two magic methods is to control the ongoing serialization process. __sleep() method returns an array of property names to be serialized. If this method is not defined then all properties are serialized.

Output:

Exporting variables

The magic method __set_state() of a class is produced in the exported string when we use var_export() function on the instance of the target object.

A variable can be exported to a parsable string representation by using var_export() function. This method is similar to var_dump() but the difference is that var_export() returns a valid PHP code. Which we can import in our program and can reuse it later. For example: Output:

Exported var returns a form which would expect a static method call __set_state() on object A and pass the exported object property array. That happens when we try to convert it to PHP variable again. We are supposed to define __set_state() method in our class and recreate the object instance from the array.

One way to reuse the exported string to manually copy paste the code and use it. Another way is to use the function eval(), which is not recommended.

Output:

Controlling debug info

The magic method __debugInfo() is triggered when we use var_dump() on the target object.

If this method isn't defined on an object, then all public, protected and private properties will be shown. If it is defined, then it should return an associative array of properties which we want to show in var_dump() call.

Output:
Cheat

Php 7 Cheat Sheet Download


Is this a piece of cake for you? Then check the PHP Syntax Exam :-)
The PHP Documentation Group has now added the Appendix K. PHP type comparison tables to the official PHP manual.

Empty() & Co, Special Values

gettype()empty()is_null()isSet()(bool)
$x = ';stringtruefalsetruefalse
$x = null;NULLtruetruefalsefalse
var $x; (not set)NULLtruetruefalsefalse
$x = array();arraytruefalsetruefalse
$x = false;booleantruefalsetruefalse
$x = 15;integerfalsefalsetruetrue
$x = 1;integerfalsefalsetruetrue
$x = 0;integertruefalsetruefalse
$x = -1;integerfalsefalsetruetrue
$x = '15';stringfalsefalsetruetrue
$x = '1';stringfalsefalsetruetrue
$x = '0';stringtruefalsetruefalse
$x = '-1';stringfalsefalsetruetrue
$x = 'foo';stringfalsefalsetruetrue
$x = 'true';stringfalsefalsetruetrue
$x = 'false';stringfalsefalsetruetrue

Note: empty() and isSet() don't give a warning when the variable has not been defined before.

A windows-like file manager to organize your remote files. more ...

comparison with

truefalse10-1'1''0''-1''1.3''1.30'1.31.30array()'foo''
truetruefalsetruefalsetruetruefalsetruetruetruetruetruefalsetruefalse
falsefalsetruefalsetruefalsefalsetruefalsefalsefalsefalsefalsetruefalsetrue
1truefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalse
0falsetruefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsetruetrue
-1truefalsefalsefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsefalse
'1'truefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalse
'0'falsetruefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalse
'-1'truefalsefalsefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsefalse
'1.3'truefalsefalsefalsefalsefalsefalsefalsetruetruetruetruefalsefalsefalse
'1.30'truefalsefalsefalsefalsefalsefalsefalsetruetruetruetruefalsefalsefalse
1.3truefalsefalsefalsefalsefalsefalsefalsetruetruetruetruefalsefalsefalse
1.30truefalsefalsefalsefalsefalsefalsefalsetruetruetruetruefalsefalsefalse
array()falsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsetruefalsefalse
'foo'truefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsetruefalse
'falsetruefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsetrue

comparison with

truefalse10-1'1''0''-1''1.3''1.30'1.31.30array()'foo''
truetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalse
falsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalse
1falsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalse
0falsefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalse
-1falsefalsefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalse
'1'falsefalsefalsefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalse
'0'falsefalsefalsefalsefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalse
'-1'falsefalsefalsefalsefalsefalsefalsetruefalsefalsefalsefalsefalsefalsefalse
'1.3'falsefalsefalsefalsefalsefalsefalsefalsetruefalsefalsefalsefalsefalsefalse
'1.30'falsefalsefalsefalsefalsefalsefalsefalsefalsetruefalsefalsefalsefalsefalse
1.3falsefalsefalsefalsefalsefalsefalsefalsefalsefalsetruetruefalsefalsefalse
1.30falsefalsefalsefalsefalsefalsefalsefalsefalsefalsetruetruefalsefalsefalse
array()falsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsetruefalsefalse
'foo'falsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsetruefalse
'falsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsetrue