Correctly understanding the eight data types in PHP is essential to a solid foundation in development. Come refresh your knowledge of the scalar types, compound types, and special data types used in PHP, and learn about proper usage of each. Review type juggling, learn some common data type traps to avoid, and how to code defensively to prevent having the data type of a variable change unexpectedly. Finally learn how unit tests can help verify that code is handling data types correctly.
2. 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
5. 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
23. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Integer
• $number = 16;
• Scalar type
• Positive or negative: -16 or 16
• is_int or is_integer
24. 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
25. 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
26. 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
28. 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
29. 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)
31. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float
• Precision varies by platform
• Limited precision
• Uses base 2 under the hood
• Prone to accuracy problems
32. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float
• (0.1 + 0.7) * 10 = 7.9999…
• floor((0.1 + 0.7) * 10) = 7
33. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float
• Use libraries for float math like BC Math or gmp
• bcadd, bcmul
• gmp_add, gmp_mul
34. 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)
35. 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)
36. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Float
• Keep precision in mind
• Use libraries for accuracy
45. 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
46. 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
47. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array
• foreach ($array as $key => $value) { … }
• foreach ($array as &$value) { … }
• for ($i = 0; $i < count($array); $i++) { … }
48. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Array
• Many useful array functions
• ksort
• asort
• array_keys
• array_key_exists
53. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object
• $var = new X;
• Compound type
• is_class
• instanceof
54. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object
• $var = new X;
• $var = new X($value);
• $var->doSomething($parameter);
• $var::staticMethod();
• $var::SOME_CONSTANT;
55. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object
• Constants
• Properties
• Methods
• Magic methods
• Visibility modifiers
• Final keyword
56. 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) { … }
}
58. 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
59. 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();
60. 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
61. 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() { … }
}
62. 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
63. 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);
64. 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 { … }
65. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Object
• Heavily used with PHP applications
• Advanced functionality
• Inheritance
• Code reuse
72. 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
73. IDENTIFY AND DEFINE
DATA TYPES IN PHP
Resource
• $resource = new mysqli(…);
• $handle = fopen($fileName, ‘r’);
• $privateKey = openssl_pkey_new([…]);
74. 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
79. 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
80. 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
{ … }
81. 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
82. DEFENSIVE CODING
DATA TYPES IN PHP
Comparison
Operators
Loose Strict
Operator == ===
Type Check No Yes
Type
Conversion
Yes No
84. 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
85. 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
86. 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’
87. DEFENSIVE CODING
DATA TYPES IN PHP
Type Casting
• Manual
• Cast variable as a specific type
• (bool) ‘false’ === true
• (boolean) 1 === true
88. 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
89. 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
90. 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{}
91. 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
93. UNIT TESTS
DATA TYPES IN PHP
Unit Tests
• Automated way to test code
• Data type checks
• Value checks
• Code behaves as expected
94. 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
95. 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 PHPUnitFrameworkTestCase;
class FilenameTest extends TestCase { … }
96. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• Focus today is on data types
• Data providers to provide test data sets
97. 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
• ===
98. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• Use setUp to set class
• protected function setUp() {
parent::setup();
$this->intMath = new IntMath;
}
99. 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]
];
}
100. 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
101. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• assertFalse($condition [, $message])
• assertNotFalse($condition [, $message])
• assertTrue($condition [, $message])
• assertNotTrue($condition [, $message])
102. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• assertNull($variable [, $message])
• assertNotNull($variable [, $message])
103. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• assertInstanceOf($expected, $actual [, $message])
• assertContainsOnlyInstancesOf($classname, $haystack [,
$message])
• Instance checks in array or Traversable
104. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• assertLessThan
• assertLessThanOrEqual
• assertGreaterThan
• assertGreaterThanOrEqual
105. UNIT TESTS
DATA TYPES IN PHP
Create Class With Tests
• assertRegExp($pattern, $string [, $message])
• assertNotRegExp
107. DATA TYPES IN PHP
SUMMARY
• 8 data types
• string
• integer
• float
• boolean
• array
• object
• null
• resource
108. 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