Coding Practice - PHP (Codeacademy)

This article contains my notes from the Codeacademy PHP course. This course covered the very basics of PHP, from definition and use of variables and arrays, to functions, to classes and inheritence.

At this point, I'm seeing lots of overlap between the concepts covered for PHP and those covered for previous languages, so my notes will focus on the differences between languages rather than repeating commonalities. That means syntax, and behavioural differences when they appear.


INTRODUCTION

PHP is a server-side scripting language. It is commonly used alongside HTML and processed to modify their content using information only the server has, before that page is sent along to the client's browser.

PHP should be used in .php files, but those files can contain HTML code.

PHP files containing HTML should start with te header <!DOCTYPE html> and html should be placed inside <html></html> tags

The PHP code in these files should be contained within a self-closing tag: <?php ... ?>


COMMENTS

All the typical HTML/CSS/Javascript comment formats are supported

// Single-line comment

/* Multi-line comment*/

<!-- Another multi-line comment -->


OPERATORS

Strings can be concatenated with "part1" . "part2"

Addition, subtraction, multiplication, division and modulo are the usual + - * / %

Comparisons are the usual > < <= >= == !=


VARIABLES

Variable names are prefixed with $, like $name = "somename"

Types are implicit


IF/ELSEIF/ELSE/SWITCH

if(condition){
    result;
}
elseif(condition2){
    result2;
}
else{
    result3;
}


switch($myVar){
    case val1:
        result1;
        break;
    case val2:
        result2;
        break;
    default:
        result3;
}

As with other languages, a case which doesn't end in "break" will fall through to execute the results of other cases until it reaches a break or the end of the switch statement.


Switch statements can also be defined without usign curly brackets at all. The "alternative syntax" is

switch($somevar):

    cases...

endswitch;


SIMPLE ARRAYS

$myArray = array(val1, val2, val3);

Elements can be retrieved and modified by index using [] or {}. This isn't something I see in a lot of languages.

Multi-dimensional arrays are supported, and can be accessed like $myArray[$val][$val2]


Individual elements of arrays can be deleted using "unset($myArray[index])," which actually shortens the array and updates the indexes of all subsequent elements.

Entire arrays can be deleted using unset($myArray). Presumably this would throw an "undefined variable" error if you tried to retrieve the value of the variable after unsetting it.


ASSOCIATIVE ARRAYS

PHP arrays can also store key-value pairs, effectiely turning them into maps/dictionaries.

$myAssociativeArray = ("key1"=>"val1", "key2"=>2, "someOtherKey"=>"blue");

The values in an associative array can be accessed both by key and by index. In the above example, $myAssociativeArray["key2"] and $myAssociativeArray[1] would both return 2.

"foreach ($array as $key=>$val)" lets us iterate through all the key-value pairs of an associative array, while accessing both the key and the value in each iteration.

 

FOR LOOPS

PHP supports both iterator-focued and array-focused loops.

for ($iterator = 0; i < $someVal; iterator++){
    someCode;
}


foreach($myList as $myElement){}
    someCode($myElement);
}

 

WHILE LOOPS

while(condition){
    someCode;
}

while(cond):
    someCode;
endwhile;


do{
    someCode;
} while(condition);


BUILT-IN FUNCTIONS

echo "sometext"; will print sometext to output. If the PHP tag were placed within an HTML h1 tag, the result would appear to a browser as "sometext" in h1 font.

strlen($myString) returns the length of myString

substr($myString, $left, $right) returns the substring of myString starting at the left index up to but not including the right index.

strtoupper($myString) returns the string entirely in upper case
strtolower($myString), you can guess

$strpos($myString, $mySubstring) returns the left index of the first occurence of substring in string. If substring isn't found, it returns false. Be careful with the `==`operator here, because PHP will automatically convert between 0 and False, which could make a "substring found at index 0" result look like "substring not found." To be safe, use "===".

round($myNum, $dec) returns myNum rounded to dec places.

rand($lower, $upper) returns a pseudorandom number between lower and upper.

array_push($myArray, $someElement) adds someElement to the end of myArray

count($myArray) returns the number of elements in myArray

sort($myArray) sorts $myArray of numbers in ascending order, and does not return a value. Presumably it works on string too, but this behaviour is nebulous.

rsort($array) is reverse-sort.

join("separator", $myArray) returns a string containing the elements of myArray separated by separator.


DEFINING FUNCTIONS

function myFunction(param1, param2){
    someCode;
    return someVal;
}

myFunction(arg1, arg2);

 

CLASS DEFINITION

We define classes, which contain properties and methods.

class myClass {
    $myProp = 1;
    function myMethod($param1){
        doSomething;
    }

}

$myInstance = new myClass();
$myInstance->myProp = 2;
$someVar = $myInstance->myFunc(7);


---

Classes can optionally contain constructors, which must be named __construct()

class myClass{
    __construct($arg1, $arg2){
        $this->prop1 = $arg1;
        $this->prop2 = $arg2;
    }
}


INHERITENCE

Classes can inherit properties and methods with an "is a" relationship, using the "extends" keyword

class Square extends Shape{
}

Simply creating another method or property with the same name as the inherited one will override the inheritance

property_exists(objInstance, "propName") returns true if objInstance has a property named propName
method_exists(objInstance, "methName") does the same, but for methods instead of properties

CLASS-SCOPE

The "->" operator is used to access properties and methods in an instance of a class.

The "::" operator is used to access properties and methods in the original definition of a class, rather than an instance. For example, this could be useful for calling a parent's version of an overridden method.

The "final" keyword (ie final public function myFunc(){}) will prevent that property/function from being overridden.

Class-scoped variables and methods are those defined in the class's original definition, rather than in an instance of a class. They can be accessed using "::".  This is useful for accessing a parent's version of an overridden method, for example.


The "const" keyword (ie const myVar = 17) prevents the given variable from being changed after definition.

The "static" keyword (ie static myVar = 23) allows variables defined in the base class to be directly accesed without going through an instance of the class.