110
DATA TYPES IN PHP MARK NIEBERGALL https://joind.in/talk/6d7f9

Data Types In PHP

Embed Size (px)

Citation preview

Page 1: Data Types In PHP

DATA TYPES IN PHP

MARK NIEBERGALL

https://joind.in/talk/6d7f9

Page 2: Data Types In PHP

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

Page 3: Data Types In PHP

ABOUT MARK NIEBERGALL

DATA TYPES IN PHP

Page 4: Data Types In PHP

ABOUT MARK NIEBERGALL

DATA TYPES IN PHP

Page 5: 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

Page 6: Data Types In PHP

DATA TYPES IN PHP

Page 7: 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

Page 8: Data Types In PHP

CAN YOU NAME ALL THE DATA TYPES?

Page 9: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

• 8 data types • 4 scalar • 2 compound • 2 special

Page 10: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

• Scalar • string • integer • float (double) • boolean

• Compound • array • object

• Special • null • resource

Page 11: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Scalar Compound Special

string array null

integer object resource

float

boolean

Page 12: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Scalar Compound Special

‘Hello world’ [1, 2, 3] null

123 new X fopen

12.34

TRUE

Page 13: Data Types In PHP

STRING

Page 14: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

String • $var = ‘Hello world!’; • Series of characters • Up to 2GB • Scalar type • is_string

Page 15: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

String • $name = ‘Alice’; • Single quote: $var = ‘Hello $name’; • Output: Hello $name

Page 16: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

String • $name = ‘Alice’; • Double quote: $var = “Hello $name”; • Output: Hello Alice

Page 17: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

String • $name = ‘Alice’; • Heredoc: $var = <<<EOD

Hello $name EOD;

• Output: Hello Alice

Page 18: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

String • $name = ‘Alice’; • Nowdoc: $var = <<<‘EOD’

Hello $name EOD;

• Output: Hello $name

Page 19: Data Types In PHP

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

Page 20: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

String • $escaped = ‘\t’;

• Output: 't'

• $escaped = “\t”; • Output: ‘ ‘

Page 21: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Page 22: Data Types In PHP

INTEGER

Page 23: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Integer • $number = 16; • Scalar type • Positive or negative: -16 or 16 • is_int or is_integer

Page 24: Data Types In PHP

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

Page 25: Data Types In PHP

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

Page 26: Data Types In PHP

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

Page 27: Data Types In PHP

FLOAT

Page 28: Data Types In PHP

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

Page 29: Data Types In PHP

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)

Page 30: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Float • $var = 12.34 • $var = 12.3e4 • $var = 12E-3

Page 31: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Float • Precision varies by platform • Limited precision • Uses base 2 under the hood • Prone to accuracy problems

Page 32: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Float • (0.1 + 0.7) * 10 = 7.9999… • floor((0.1 + 0.7) * 10) = 7

Page 33: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Float • Use libraries for float math like BC Math or gmp

• bcadd, bcmul • gmp_add, gmp_mul

Page 34: Data Types In PHP

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)

Page 35: Data Types In PHP

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)

Page 36: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Float • Keep precision in mind • Use libraries for accuracy

Page 37: Data Types In PHP

BOOLEAN

Page 38: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Boolean • $var = true; • Scalar type • Boolean or Bool • Only two possible values: true or false • is_bool

Page 39: Data Types In PHP

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

Page 40: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Boolean • true === true • false === false

Page 41: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Boolean • Good to work with • Simplify checks

Page 42: Data Types In PHP

ARRAY

Page 43: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Array • $var = [1, 2, 3]; • Compound type • is_array

Page 44: Data Types In PHP

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);

Page 45: Data Types In PHP

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

Page 46: Data Types In PHP

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

Page 47: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Array • foreach ($array as $key => $value) { … } • foreach ($array as &$value) { … } • for ($i = 0; $i < count($array); $i++) { … }

Page 48: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Array • Many useful array functions • ksort • asort • array_keys • array_key_exists

Page 49: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Array • array_merge • array_intersect • array_column

Page 50: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Array • array_push • array_pop • array_shift • array_unshift • array_splice

Page 51: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Array • Use wisely • Use available array functions • Avoid overly nested arrays • Watch key casting

Page 52: Data Types In PHP

OBJECT

Page 53: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Object • $var = new X; • Compound type • is_class • instanceof

Page 54: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Object • $var = new X; • $var = new X($value); • $var->doSomething($parameter); • $var::staticMethod(); • $var::SOME_CONSTANT;

Page 55: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Object • Constants • Properties • Methods • Magic methods • Visibility modifiers • Final keyword

Page 56: Data Types In PHP

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) { … } }

Page 57: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Object • Abstract • Interface • Trait

Page 58: Data Types In PHP

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

Page 59: Data Types In PHP

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();

Page 60: Data Types In PHP

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

Page 61: Data Types In PHP

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() { … } }

Page 62: Data Types In PHP

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

Page 63: Data Types In PHP

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);

Page 64: Data Types In PHP

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 { … }

Page 65: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Object • Heavily used with PHP applications • Advanced functionality • Inheritance • Code reuse

Page 66: Data Types In PHP

NULL

Page 67: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Null • $var; • $var = null; • Special type • Represents no value • is_null

Page 68: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Null • public function doNothing() {} • $value = $object->doNothing();

Page 69: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Null • $value = null; • Works: empty($value) === true • Best: is_null($value) === true

Page 70: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Null • unset($value) • $value becomes null

Page 71: Data Types In PHP

RESOURCE

Page 72: Data Types In PHP

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

Page 73: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Resource • $resource = new mysqli(…); • $handle = fopen($fileName, ‘r’); • $privateKey = openssl_pkey_new([…]);

Page 74: Data Types In PHP

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

Page 75: Data Types In PHP

IDENTIFY AND DEFINE

DATA TYPES IN PHP

Resource • Cannot cast to resource

Page 76: Data Types In PHP

DEFENSIVE CODING

Page 77: Data Types In PHP

DEFENSIVE CODING

DATA TYPES IN PHP

Defensive Coding • Hope for the best and prepare for the worst • Type hinting • Type checking • Type casting

Page 78: Data Types In PHP

DEFENSIVE CODING

DATA TYPES IN PHP

Page 79: 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

Page 80: Data Types In PHP

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

{ … }

Page 81: Data Types In PHP

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

Page 82: Data Types In PHP

DEFENSIVE CODING

DATA TYPES IN PHP

Comparison Operators Loose Strict

Operator == ===

Type Check No Yes

Type Conversion Yes No

Page 83: Data Types In PHP

DEFENSIVE CODING

DATA TYPES IN PHP

Type Casting • Automatic • Manual

Page 84: Data Types In PHP

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

Page 85: Data Types In PHP

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

Page 86: Data Types In PHP

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’

Page 87: Data Types In PHP

DEFENSIVE CODING

DATA TYPES IN PHP

Type Casting • Manual

• Cast variable as a specific type • (bool) ‘false’ === true • (boolean) 1 === true

Page 88: Data Types In PHP

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

Page 89: Data Types In PHP

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

Page 90: Data Types In PHP

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{}

Page 91: Data Types In PHP

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

Page 92: Data Types In PHP

UNIT TESTS

Page 93: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Unit Tests • Automated way to test code • Data type checks • Value checks • Code behaves as expected

Page 94: Data Types In PHP

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

Page 95: Data Types In PHP

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 { … }

Page 96: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • Focus today is on data types • Data providers to provide test data sets

Page 97: Data Types In PHP

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 • ===

Page 98: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • Use setUp to set class

• protected function setUp() { parent::setup(); $this->intMath = new IntMath; }

Page 99: Data Types In PHP

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] ]; }

Page 100: Data Types In PHP

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

Page 101: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • assertFalse($condition [, $message]) • assertNotFalse($condition [, $message]) • assertTrue($condition [, $message]) • assertNotTrue($condition [, $message])

Page 102: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • assertNull($variable [, $message]) • assertNotNull($variable [, $message])

Page 103: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • assertInstanceOf($expected, $actual [, $message]) • assertContainsOnlyInstancesOf($classname, $haystack [,

$message]) • Instance checks in array or Traversable

Page 104: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • assertLessThan • assertLessThanOrEqual • assertGreaterThan • assertGreaterThanOrEqual

Page 105: Data Types In PHP

UNIT TESTS

DATA TYPES IN PHP

Create Class With Tests • assertRegExp($pattern, $string [, $message]) • assertNotRegExp

Page 106: Data Types In PHP

SUMMARY

Page 107: Data Types In PHP

DATA TYPES IN PHP

SUMMARY

• 8 data types • string • integer • float • boolean • array • object • null • resource

Page 108: Data Types In PHP

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

Page 109: Data Types In PHP

QUESTIONS?https://joind.in/talk/6d7f9

Page 110: Data Types In PHP

SOURCES

DATA TYPES IN PHP

• php.net • https://phpunit.de/manual/current/en/ • https://getcomposer.org/doc/00-intro.md