This document provides an overview of basic PHP concepts, including what PHP is, how to work with variables, naming conventions, numbers and casting, operators, conditions, arrays, limiting nested code, object-oriented programming with classes, and some examples of working with a User class and extending it to a Reseller class. It covers fundamental PHP syntax and structures to get started with the language.
3. What is PHP?
• Hypertext PreProcessor
• Built on C
• Made for the web, but can run on the
command line
• We run all our processing scripts via the
CLI
4. Variables
• The $ is used to prefix a string, which denotes a variable
• $name = “BOB”; //this assigns the variable
• $sentence = “my name is $name”; // what will this out put?
• $concatenate = “my name is ”.$name; //what will this
output?
• Display information
• echo $sentence;
• print($sentence);
5. Naming Variables
• $name; // lower case for single words
• $lastName; //camel case for more than one word
• $animalsArray = (‘cow’,’dog’); // not good
• $animals = (‘cow’,’dog’);
• $userObj = new User() // not good
• $user = new User();
• http://www.php-fig.org/psr/
7. Numbers
• Everything in PHP is cast to an integer by default
• echo 2 + 2; //4
• echo '2' + 2; //4
• ;echo '2' + "2"; //4
• echo 2 + 'c’; //2
8. Casting
• What is casting?
• Casting means making a value a particular type
• $i = 2.332242;
• (int) $i; //2
• (float) $i; // 2.332242
• (string) $i; // 2.332242
9. Casting
• Why do we care about casting?
• When we interact with data, the language you work with may assume
things
• If you parse and XML message - https://en.wikipedia.org/wiki/XML
• <amount>10.32</amount>
• Using an XML parser, the 10.32 will be assumed as an integer, 10 and
not 10.32
• Casting the value will give you the 10.32
• These things are picked up as you learn to code
10. Operations
• < //less than
• > //greater than
• <= //less than or equal to
• >= //greater than or equal to
• = //assignment $i =1;
• == //equality (1 == true)
• === //type equlity (1 === true)
• ! //negation - you should be carful (!$bob instanceof
Class) rather (!($bob instanceof Class))
16. Arrays
• Can be used to represent a data source [database, file,
etc.]
• There are many built in functions for arrays.
http://php.net/manual/en/function.array.php
• array_sum($amounts); //R24.23;
• Database queries can be returned as arrays
20. Nesting
• Keep your nesting to a minimal
• The deeper you nest the more complex you code
becomes
• The more it is to debug
• Refactor if your code becomes a mess.
• Make smaller functions for each complex bit.
• Avoid else
• Return early is not a bad thing