Upload
sacheen-dhanjie
View
170
Download
0
Embed Size (px)
Citation preview
Basics of PHPSACHEEN DHANJIE
Sacheen DhanjieSenior Developer @ Afrihost.com
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
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);
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/
Numbers• echo 2 + 2; ?• echo '2' + 2; ?• ;echo '2' + "2"; ?• echo 2 + 'c’; ?
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
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
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
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))
What if $bob?
Bob Ross or just Ross?
What if $bob• (!$bob)
• If $bob was null; //true• If $bob was 1; //false• If $bob was false; //true• If $bob was 0; //true
Conditions
Conditions
Arrays
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
I hate else
Limit Nesting
Any suggestions to neaten this up?
Limit Nesting
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
Do one thing and do it well
Simple Objects – Object Oriented Programing
• Classes• Can be instantiated• Has instance variables• getters• Setters [mutators]• Can be extended• Accessibility
• - public / private / protected
User Class
Using the User Class
Extend the User Class
Using the Reseller Class
Cool Functions
Something Cool