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.
Features/Syntax | Description/examples |
---|---|
classA 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' keywordTo create an instance of a class, new keyword is used pseudo-variable $thisThe reference to the current object, only used within the class. Object operator | Output: |
VisibilityThe visibility keywords (public, protected, private) determines how an object properties/methods are accessible:
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 constantsJust 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 methodsClass 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 destructorsA constructor function A destructor is a special function 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/destructParent 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 keywordSimilar 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 overridingMethod 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 classesAn 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: |
InterfacesLike 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 interfacesA 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: |
TraitsA 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..
| Output: |
Final keywordA method declared with final keyword cannot be overridden by a subclass. A class declared with final keyword cannot be extended. | Output: Output: |
Objects equality
| Output: |
Object iterationBy default all visible properties can be iterated using foreach loop. To control iteration process we can implement built-in Iterator interface. | Output: |
Auto-loading ClassesFor 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 methodsThese 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.
| Output: |
Method overloading__call(), __callStaticThis is a way to dynamically create object methods which do not exist or are inaccessible.
| 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 variablesThe 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 infoThe 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: |
Php 7 Cheat Sheet Download
comparison with
comparison with
|