Cheatography
https://cheatography.com
Basic Syntax
Files start with |
<?php |
Single line comment |
// a comment |
Multi-line comment |
/ comment / |
End of instruction |
; |
Include code from another file |
require_once('some_file.php'); |
Classes and Objects
class SomeClass {
private $property;
public $anotherProperty;
protected $yetAnotherProperty = null;
public function __construct($arg=null)
{
$this->property = $arg;
}
public function someMethod()
{
echo “Hi”;
}
public function getProperty()
{
return $this->property;
}
public function setProperty( $p )
{
$this->property = $p;
}
}
$myObject = new SomeClass( “123” );
echo $myObject->getProperty(); // 123
$myObject->property; // ERROR:private |
|
|
Variables
$variableName; |
$variableName = "Some String"; |
$variableName = 'Some String'; |
$variableName = strtoupper('text'); |
$variableName = 5; |
$variable = "Some {$otherVariable} info"; |
echo $variableName; // output |
$newVar = $var1 . $var2; // concatenation |
Functions
function multiply($arg1, $arg2)
{
return $arg * $arg2;
}
$param = 4;
$param2 = 8;
$answer = multiply($param, $param2); |
Control Structure: IF
// if something is true do something else
if( $something == true ) {
doSomethingElse();
} elseif( $something == false ) {
// however, if something is false, do something
doSomething();
} else {
// otherwise, lets do nothing
doNothing();
} |
Control Structure: Loops
foreach( $myArray as $key => $value ) {
echo “My array has the value {$value} stored against the key {$key}<br />”;
}
while( someCondition == true ) {
echo ‘hello’;
} |
|
|
Numerical Operations
Addition |
$variable = $variable + 5; |
Subtraction |
$variable = $variable - 5; |
Multiplication |
$variable = $variable * 5; |
Division |
$variable = $variable / 5; |
Arrays
Create |
$myArray = array(); |
Push into |
$myArray[] = "Something"; |
Push to associative |
$myArray['key'] = "Value"; |
Create numeric |
$myArray = array('value', 'value2'); |
Create associative |
$a = array('key'=>'val'); |
Print from numeric |
echo $myArray[0]; |
Print from associative |
echo $myArray['key']; |
Associative arrays |
Keys are strings |
Numeric arrays |
Keys are numbers: 0,1,2,3,4 |
Control Structure: Switch
switch( $someVariable ) {
case 1:
echo “Some variable equals 1”;
break;
case “cheese”
echo “Some variable equals cheese”;
break;
default:
echo “No idea”;
break;
} |
|
Created By
Metadata
Favourited By
and 11 more ...
Comments
Sergey 13:00 17 Sep 15
There is a mistake in multiline comment. Should be /* */
Add a Comment
Related Cheat Sheets