Upload
mark-niebergall
View
220
Download
0
Embed Size (px)
Citation preview
ABOUT MARK NIEBERGALL
DATA TYPES IN PHP
• PHP since 2005 • Masters degree in MIS • Senior Software Engineer • Team Lead • Drug screening project • President of Utah PHP User Group (UPHPU) • SSCP, CSSLP Certified and SME for (ISC)2 • PHP, databases, JavaScript • Drones, fishing, skiing, father, husband
ABOUT MARK NIEBERGALL
DATA TYPES IN PHP
ABOUT MARK NIEBERGALL
DATA TYPES IN PHP
UPHPU
DATA TYPES IN PHP
• Third Thursday of each month at 7pm • Venue is Vivint in Lehi (3401 Ashton Blvd) • Variety of PHP related topics • Mostly local speakers, occasional traveling speaker • Networking with other developers, companies • Professional development • uphpu.org
DATA TYPES IN PHP
OVERVIEW
DATA TYPES IN PHP
• Identify and define each type • Proper usage • Type juggling • Data type traps
• Defensive coding • Unit tests
CAN YOU NAME ALL THE DATA TYPES?
IDENTIFY AND DEFINE
DATA TYPES IN PHP
• 8 data types • 4 scalar • 2 compound • 2 special
IDENTIFY AND DEFINE
DATA TYPES IN PHP
• Scalar • string • integer • float (double) • boolean
• Compound • array • object
• Special • null • resource
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Scalar Compound Special
string array null
integer object resource
float
boolean
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Scalar Compound Special
‘Hello world’ [1, 2, 3] null
123 new X fopen
12.34
TRUE
STRING
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $var = ‘Hello world!’; • Series of characters • Up to 2GB • Scalar type • is_string
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $name = ‘Alice’; • Single quote: $var = ‘Hello $name’; • Output: Hello $name
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $name = ‘Alice’; • Double quote: $var = “Hello $name”; • Output: Hello Alice
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $name = ‘Alice’; • Heredoc: $var = <<<EOD
Hello $name EOD;
• Output: Hello Alice
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $name = ‘Alice’; • Nowdoc: $var = <<<‘EOD’
Hello $name EOD;
• Output: Hello $name
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $name = ‘Alice’; • $var = ‘Hello ‘ . $name; • $var = “Hello $name”; • $var = “Hello {$name}”; • $var = “Hello {$person[‘name’]}”; • $var = “Hello {$person->name}”; • Output: Hello Alice
IDENTIFY AND DEFINE
DATA TYPES IN PHP
String • $escaped = ‘\t’;
• Output: 't'
• $escaped = “\t”; • Output: ‘ ‘
IDENTIFY AND DEFINE
DATA TYPES IN PHP
INTEGER
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Integer • $number = 16; • Scalar type • Positive or negative: -16 or 16 • is_int or is_integer
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Integer • Decimal (base 10): 16 • Hexadecimal (base 16, leading 0x): 0x10 • Octal (base 8, leading 0): 020 • Binary (base 2, leading 0b): 0b10000
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Integer • Max 2,147,483,647 on 32-bit system • Max 9,223,372,036,854,775,807 on 64-bit system • Becomes a float if too big
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Integer • Automatically converted to float in math where result is not a
whole number • 16 / 2 = integer 8 • 16 / 3 = float 5.3333333333333 • (int) ((0.1 + 0.7) * 10) = (int) 7
• Precision with floats • Float to integer always rounded toward zero
FLOAT
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • $var = 12.34; • Scalar type • Double • Floating-point number • Real numbers • is_float, is_double, or is_real
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • Uses IEEE 754 standard for calculations
• Arithmetic formats • Interchange formats • Rounding rules • Operations • Exception handling (overflow, divide by zero)
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • $var = 12.34 • $var = 12.3e4 • $var = 12E-3
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • Precision varies by platform • Limited precision • Uses base 2 under the hood • Prone to accuracy problems
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • (0.1 + 0.7) * 10 = 7.9999… • floor((0.1 + 0.7) * 10) = 7
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • Use libraries for float math like BC Math or gmp
• bcadd, bcmul • gmp_add, gmp_mul
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • BCMath Arbitrary Precision Mathematics • bcxxx($leftOperand, $rightOperand [, $scale]) • bcscale($scale) • bcadd($a, $b) • bcmul($a, $b) • bcdiv($a, $b)
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • GNU Multiple Precision • gmp_xxx($leftOperand, $rightOperand [, $rounding])
• GMP_ROUND_ZERO • GMP_ROUND_PLUSINF • GMP_ROUND_MINUSINF
• gmp_init($number) • gmp_add($a, $b) • gmp_mul($a, $b) • gmp_div($a, $b, GMP_ROUND_ZERO)
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float • Keep precision in mind • Use libraries for accuracy
BOOLEAN
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Boolean • $var = true; • Scalar type • Boolean or Bool • Only two possible values: true or false • is_bool
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Boolean • $var = true; • 0 == false • 1 == true • 2 == true • -1 == true • 3.45 == true • ‘abc’ == true • ‘false’ == true
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Boolean • true === true • false === false
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Boolean • Good to work with • Simplify checks
ARRAY
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • $var = [1, 2, 3]; • Compound type • is_array
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • $var = [1, 2, 3, 4.56]; • $var = [‘abc’, ‘xyz’]; • $var = [‘fruit’ => ‘apple’, ‘vegetable’ => ‘carrot’]; • $var = array(‘key’ => ‘value’); • $var[‘key’] = ‘value’; • $var[] = ‘value’; • $var{123} = ‘value’; • $var = explode(‘,’, $csv);
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • Ordered map • Keys and values
• Keys are integer or string • Value can be of any data type • If adding value to array then key = max numeric key + 1
where max numeric key is max that has existed since last re-index
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Data Type Key Key Cast As
string ‘abc123' ‘abc123'
string ‘123’ 123
float 12.34 12
bool true 1
null null ‘'
array […] Illegal offset
object new X Illegal offset
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • foreach ($array as $key => $value) { … } • foreach ($array as &$value) { … } • for ($i = 0; $i < count($array); $i++) { … }
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • Many useful array functions • ksort • asort • array_keys • array_key_exists
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • array_merge • array_intersect • array_column
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • array_push • array_pop • array_shift • array_unshift • array_splice
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array • Use wisely • Use available array functions • Avoid overly nested arrays • Watch key casting
OBJECT
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • $var = new X; • Compound type • is_class • instanceof
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • $var = new X; • $var = new X($value); • $var->doSomething($parameter); • $var::staticMethod(); • $var::SOME_CONSTANT;
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Constants • Properties • Methods • Magic methods • Visibility modifiers • Final keyword
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object class RainbowTrout extends Fish implements MarineLife { use Camouflage; const SPECIES = ‘Rainbow Trout’; protected $age; public function swim() { … } protected function breathe() { … } public function eat(Food $food) { … } private function ponder(Thought $thought) { … } }
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Abstract • Interface • Trait
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Abstract
• Vertical inheritance via extend • class Dog extends Canine • Is X a Y? • Code reusability • Ensure functionality • Only extend one class at a time • Can have multiple levels • Cannot be instantiated
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Abstract
• abstract Canine { public function wagTail() { … } abstract public function run(); }
• class Dog extends Canine { public function run() { … } }
• $dog = new Dog; $dog->wagTail(); $dog->run();
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Interface
• Class implements an interface • Define required method signatures • Does not define content of methods • Class defines the implementation • What class needs to do, not how to do it
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Interface
• interface PlayFetch { public function retrieveItem(Item $item); }
• class Dog implements PlayFetch { public function retrieveItem(Item $item) { … } }
• class Child extends Human implements PlayFetch, TakeNap { public function retrieveItem(Item $item) { … } public function fallAsleep() { … } }
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Trait
• Characteristic • Attribute • Reusable group functionality • Horizontal inheritance • Cannot be instantiated • Can use multiple traits • Vertical inheritance considerations • Dependency injection considerations
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Trait
• trait Hair { protected $color; public function setHairColor($color) { … } public function washHair($shampoo) { … } }
• class Cat extends Feline { use Hair; } • $cat = new Cat;
$cat->setHairColor(‘grey’); $cat->washHair($shampoo);
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Type hinting
• Method signatures • public function doSomething(X $x, array $y) { … }
• Doc blocks • /** @var integer */
• Method return type hint as of PHP 7 • public function sum($a, $b): integer { … }
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object • Heavily used with PHP applications • Advanced functionality • Inheritance • Code reuse
NULL
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Null • $var; • $var = null; • Special type • Represents no value • is_null
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Null • public function doNothing() {} • $value = $object->doNothing();
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Null • $value = null; • Works: empty($value) === true • Best: is_null($value) === true
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Null • unset($value) • $value becomes null
RESOURCE
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Resource • Special type • Reference to an external resource
• Database connection • Open files • Certificates • Image canvas
• get_resource_type • is_resource
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Resource • $resource = new mysqli(…); • $handle = fopen($fileName, ‘r’); • $privateKey = openssl_pkey_new([…]);
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Resource • Can be closed manually • Automatically closed when no more references • Memory freed by garbage collector • Exception to the rule are persistent database connections
IDENTIFY AND DEFINE
DATA TYPES IN PHP
Resource • Cannot cast to resource
DEFENSIVE CODING
DEFENSIVE CODING
DATA TYPES IN PHP
Defensive Coding • Hope for the best and prepare for the worst • Type hinting • Type checking • Type casting
DEFENSIVE CODING
DATA TYPES IN PHP
DEFENSIVE CODING
DATA TYPES IN PHP
Type Hinting • Use heavily • Provides documentation • Supports ‘Fail fast’ • Ensures data is of correct type or instance • Makes code easier to read and understand by peers
DEFENSIVE CODING
DATA TYPES IN PHP
Type Hinting • Method parameters
• protected function doSomething(int $a, float $b, bool $c, array $d, X $x) { … }
• Method return • private function doOther(SomeClass $someClass): someClass
{ … }
DEFENSIVE CODING
DATA TYPES IN PHP
Type Checking • Use proper data type checks
• is_null instead of empty • is_float instead of is_numeric • === when possible • instanceof checks • count vs empty
DEFENSIVE CODING
DATA TYPES IN PHP
Comparison Operators Loose Strict
Operator == ===
Type Check No Yes
Type Conversion Yes No
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Automatic • Manual
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Automatic
• PHP is a loosely typed language • Variable data type can change • Particularly with going to string or integer • Unintentionally introduce defects • ‘1’ + ‘2’ === 3 • 1 + ‘1 way’ === 2
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (int) false === 0 • (int) 12.34 === 12 • (int) ‘123abc’ === 123
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (string) false === ‘’ • (string) true === ‘1’ • (string) 12.34 === ’12.34’
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (bool) ‘false’ === true • (boolean) 1 === true
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (float) ’12.34’ === 12.34 • (double) 12 === 12 • (real) ‘’ === 0
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (array) ‘scalar’ === [‘scalar’] • (array) new Exception === [‘* message’ => ‘’, ‘Exception
string’ => ‘’, ‘* code’ => 0, ‘* file’ => ‘/path/to/file.php’, ‘* line’ => 123, ‘Exception trace’ => […], ‘Exception previous’ => null] • Classname key for private • Asterisk * for protected
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (object) [1, 2, 3] becomes stdClass{public 0 = 1; public 1 = 2;
public 3 = 2;} • (object) ‘something’ becomes stdClass{public ‘scalar’ =
‘something’;} • (object) null becomes stdClass{}
DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting • Manual
• Cast variable as a specific type • (unset) ‘anything’ === null • (unset) $value === null
• returns null • $value retains existing value
UNIT TESTS
UNIT TESTS
DATA TYPES IN PHP
Unit Tests • Automated way to test code • Data type checks • Value checks • Code behaves as expected
UNIT TESTS
DATA TYPES IN PHP
Setup • Via composer
• Add to composer.json: • “require-dev”: {“phpunit/phpunit”: “5.4.*”}
• composer update • Via download
• wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar sudo mv phpunit.phar /usr/local/bin/phpunit
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • Create /tests/ directory • Files named *Test.php • If using composer
• require_once __DIR__ . ‘/../vendor/autoload.php’; • use PHPUnit\Framework\TestCase;
class FilenameTest extends TestCase { … }
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • Focus today is on data types • Data providers to provide test data sets
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertEquals($expected, $actual [, $message])
• Value is equal • No data type check • ==
• assertSame($expected, $actual [, $message]) • Value is equal • Data type is same • ===
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • Use setUp to set class
• protected function setUp() { parent::setup(); $this->intMath = new IntMath; }
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • Use data providers to use test data sets • /** @dataprovider intAdditionProvider */
public function testAddInts($a, $b, $expected) { $this->assertSame($expected, $this->IntMath->add($a, $b)); } public function intAdditionProvider() { return [ [0, 0, 0], [1, 2, 3], [-1, 1, 0] ]; }
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertContains($needle, $haystack [, $message, $ignoreCase])
• Value (needle) exists in haystack • Defaults to not ignore case
• assertContainsOnly($type, $haystack [, $isNativeType, $message]) • Is type the only data type in the haystack
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertFalse($condition [, $message]) • assertNotFalse($condition [, $message]) • assertTrue($condition [, $message]) • assertNotTrue($condition [, $message])
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertNull($variable [, $message]) • assertNotNull($variable [, $message])
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertInstanceOf($expected, $actual [, $message]) • assertContainsOnlyInstancesOf($classname, $haystack [,
$message]) • Instance checks in array or Traversable
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertLessThan • assertLessThanOrEqual • assertGreaterThan • assertGreaterThanOrEqual
UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests • assertRegExp($pattern, $string [, $message]) • assertNotRegExp
SUMMARY
DATA TYPES IN PHP
SUMMARY
• 8 data types • string • integer • float • boolean • array • object • null • resource
DATA TYPES IN PHP
SUMMARY
• Use data types correctly • Code defensively • Be aware of automatic type casting • Prefer strict type checks • Unit tests to ensure correct values
QUESTIONS?https://joind.in/talk/6d7f9
SOURCES
DATA TYPES IN PHP
• php.net • https://phpunit.de/manual/current/en/ • https://getcomposer.org/doc/00-intro.md