Intro to PHP Classes and Objects
Procedural vs Object-Oriented
Procedural
- running through a series of steps
- relies heavily on functions
Object-Oriented
- program organized into objects
- objects expose their methods (the interface) to the rest of the program to interact with each other
Procedural vs Object-Oriented
- You can write mostly procedural code in PHP with classes/objects, but you can't write object-oriented code without them.
- Codebases like WordPress contain a mixture of procedural and object-oriented concepts.
Classes in PHP
- Classes are blueprints used to create objects
<?php
// The blueprint
class FormSubmission {
public function validate() {
// some activity
}
}
// The object (implementation)
$form_submission = new FormSubmission();
// Another object
$another_submission = new FormSubmission();
Classes in PHP
- Inside of an object, $this refers to itself
<?php
class FormSubmission {
public function __construct() {
$this->validate();
}
public function validate() {
// some activity
}
}
$form_submission = new FormSubmission();
Classes in PHP
- Three types of "visibility" for properties and methods
- ("private" discussed on next slide)
<?php
class Thing {
public function foo() {
echo "method foo";
}
public function biz() {
$this->bar();
}
protected function bar() {
echo "method bar";
}
}
$thing = new Thing();
$thing->foo(); // => method foo
$thing->biz(); // => method bar
// => E_ERROR : type 1 -- Call to protected method Thing::bar()...
$thing->bar();
Inheritance
- Classes can be parents/children of each other
- private vs protected
<?php
class Thing {
protected function foo() {
echo "method foo";
}
private function bar() {
echo "method foo";
}
}
class AnotherThing extends Thing {}
$thing = new AnotherThing();
$thing->foo(); // => method foo
$thing->bar(); // => E_ERROR : type 1 -- Call to protected method Thing::foo()...
Static methods and properties
- Static methods and properties let you use a class without an object
- No $this - use "this"
<?php
class Thing {
public static $somevar = "some variable";
public static function foo() {
echo "grabbing " . self::$somevar;
}
}
echo Thing::$somevar; // some variable
Thing::foo(); // => grabbing some variable
Constructor
- Lets you do stuff when an object is created
<?php
class FormSubmission {
protected $is_valid;
public function __construct($somedata) {
$this->validate($somedata);
}
public function validate($data) {
// do some validation
$this->is_valid = $data . " is good to go";
}
public function is_valid() {
return $this->is_valid;
}
}
$submission = new FormSubmission('some input');
echo $submission->is_valid(); // => some input is good to go
Intro to PHP Classes and Objects
By Daniel Abernathy
Intro to PHP Classes and Objects
- 1,457