5+ years PHP
Senior PHP/Drupal Engineer
Object-Oriented PHP for Beginners | Tuts+
DEC 23, 2011 / JASON LENGSTORF
http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762
Basics of PHP
<?php
// Variables
$fruit = "apple";
<?php
// Variables
$fruit = "apple";
// Logic operators
if ( $fruit == "apple" ) {
// can include html in string output
echo "sweeeeeet!<br />";
}
// Arrays
$colors = array("blue", "purple", 'red');
// Loops
foreach ($colors as $color) {
echo $color . "<br />";
}
<?php
// Variables
$fruit = "apple";
// Logic operators
if ( $fruit == "apple" ) {
// can include html in string output
echo "sweeeeeet!<br />";
}
<?php
// Variables
$fruit = "apple";
// Logic operators
if ( $fruit == "apple" ) {
// can include html in string output
echo "sweeeeeet!<br />";
}
// Arrays
$colors = array("blue", "purple", 'red');
// Loops
foreach ($colors as $color) {
echo $color . "<br />";
}
// Functions
function color_exists($needle, $haystack) {
return in_array($needle, $haystack);
}
// assign returned output to variable
$is_brown_good = color_exists("brown", $colors);
Note the usage of these object properties in the following WordPres script
<?php
$thumb_id = get_post_thumbnail_id($post->ID);
$url = wp_get_attachment_url($thumb_id);
<img src="<?php echo $url; ?>" alt="Thumbnail for <?php echo $post->post_title; ?>" />
<?
$post->ID
$post->post_title
"Object-oriented programming is a style of coding that allows developers to group similar tasks into classes."
Before you can get too deep into the finer points of OOP, a basic understanding of the differences between objects and classes is necessary.
Developers start talking about objects and classes, and they appear to be interchangeable terms.
This is not the case.
Height
Come
Color: Gray
Eye Color: Brown
Height: 18"
Length: 36"
Weight: 30 lbs
Sit
Lay Down
Shake
Come
Create Instance
Object-Oriented Thinking
JULY 16, 2014 / RODRIGO ARAÚJO
http://www.universocomputacao.com/object-oriented-thinking/
Length
Weight
Eye Color
Color
Shake
Lay Down
Sit
Maximus
<?php
class Dog
{
// class properties
public $color;
public $eye_color;
public $height;
public $length;
public $weight;
// class methods
public function sit() {
}
public function lay_down() {
}
public function shake() {
}
public function come() {
}
}
<?php
$maximus = new Dog();
$maximus->color = "Gray";
$maximus->eye_color = "Brown";
$maximus->height = 18;
$maximus->length = 36;
$maximus->weight = 30;
?>
<?php
class Person
{
// Let's write our first property
public $name = "john";
}
<?php
class Person
{
// Let's write our first property
public $name = "john";
}
$my_person = new Person();
<?php
class Person
{
}
<?php
class Person
{
// Let's write our first property
public $name = "john";
}
$my_person = new Person();
echo $my_person->name;
<?php
class Person
{
public $name;
public $weight = 0;
public $miles = 0;
}
<?php
class Person
{
public $name;
public $weight = 0;
public $miles = 0;
// Let's write our first method
public function run($miles) {
$this->miles += $miles;
}
}
<?php
class Person
{
public $name;
public $weight = 0;
public $miles =0;
// Let's write our first method
public function run($miles) {
$this->miles += $miles;
}
}
$my_person = new Person();
$my_person->name = "john";
$my_person->weight = 100;
<?php
class Person
{
public $name;
public $weight = 0;
public $miles =0;
// Let's write our first method
public function run($miles) {
$this->miles += $miles;
$this->weight = $this->weight - $miles;
}
}
$my_person = new Person();
$my_person->name = "john";
$my_person->weight = 170;
// notice: weight is 170
var_dump($my_person);
// notice: we've lost weight from running
$my_person->run(5);
var_dump($my_person);
<?php
class Dog {
public $legs;
public $color;
public $eye_color;
public function __construct($color, $eye_color) {
$this->legs = 4;
$this->color = $color;
$this->eye_color = $eye_color;
}
}
$rover = new Dog("black/white", "light blue");
var_dump($rover);
<?php
class Dog {
public $legs = 4;
}
$rover = new Dog();
echo $rover;
<?php
class Dog {
public $legs = 4;
public function __toString() {
return "Dogs have $this->legs legs.";
}
}
$rover = new Dog();
echo $rover;
class Shape
{
public $sides;
public $fill_color;
public function __construct($sides) {
$this->sides = $sides;
}
public function get_angle() {
return 360 / $this->sides;
}
}
$hexagon = new Shape(6);
echo $hexagon->get_angle(); // --> 60
class Rectangle extends Shape
{
public $sides = 4;
public $length;
public $width;
public function __construct($width, $length){
$this->length = length;
$this->width = width;
}
}
class Square extends Rectangle
{
public function __construct($width) {
$this->length = width;
$this->width = width;
}
}
$my_square = new Square(5);
echo $my_square->get_angle(); // --> 90
class Rectangle extends Shape
{
public $sides = 4;
public $length;
public $width;
public function __construct($width, $length){
$this->length = length;
$this->width = width;
}
}
class Shape
{
public $sides;
public $fill_color;
public function __construct($sides) {
$this->sides = $sides;
}
public function get_angle() {
return 360 / $this->sides;
}
}
$hexagon = new Shape(6);
echo $hexagon->get_angle(); // --> 60
class Rectangle extends Shape
{
public $length;
public $width;
public function __construct($sides, $width, $length){
parent::__construct(4);
$this->length = length;
$this->width = width;
}
}
class Shape
{
public $sides;
public $fill_color;
public function __construct($sides) {
$this->sides = $sides;
}
public function get_angle() {
return 360 / $this->sides;
}
}
$hexagon = new Shape(6);
echo $hexagon->get_angle(); // --> 60
<?php
class Person
{
public name;
public weight = 0;
public function run($miles) {
$this->weight -= $miles;
}
}
$my_person = new Person();
// public property and method I can access
$my_person->weight = 100;
$my_person->run(5);
Can be accessed anywhere, both within the class and externally.
<?php
class Person
{
protected name;
public function get_name() {
return $this->name;
}
public function set_name($name) {
$this->name = $name;
}
}
$my_person = new Person();
// can access public methods
$my_person->set_name("Leonidas");
echo $my_person->get_name();
// but accessing protected properties would be fatal
echo $my_person->name; // --> fatal error
Can only be accessed within the class itself or in descendant classes (classes that extend the class containing the protected method).
are accessible only from within the class that defines it. This means that even if a new class extends the class that defines a private property, that property or method will not be available at all within the child class.
<?php
class Person
{
private name;
public function get_name() {
return $this->name;
}
public function set_name($name) {
$this->name = $name;
}
}
$my_person = new Person();
// can access public methods
$my_person->set_name("Leonidas");
echo $my_person->get_name();
// but accessing private properties would be fatal
echo $my_person->name; // --> fatal error
class MyClass {
public static function plusOne() {
return "The count is " . ++self::$count . ".<br />";
}
}
do
{
// Call plusOne without instantiating MyClass
echo MyClass::plusOne();
} while ( MyClass::$count < 10 );
can be accessed without first instantiating the class
Note — When accessing static properties, the dollar sign
($) comes after the scope resolution operator.
"In languages like c# and java, statics are a part of the language. You can do things like... Console.WriteLine() or int.TryParse(), String.Join() etc... these are all utilities"
Console.WriteLine();
int.TryParse();
String.Join();
Comments |When to Use Static Methods
FEB 20, 2015 / jrenton
http://verraes.net/2014/06/when-to-use-static-methods-in-php/#comment-1865595749
<?php
$time = Time::from("11:45");
<?php
$sum = Calculator::sum(1, 2);
When to Use Static Methods
JUN 14, 2014 / MATHIAS VERRAES
http://verraes.net/2014/06/when-to-use-static-methods-in-php/
Example use cases:
/**
* Returns the name of this object.
*
* @return string
*/
Example
<?php
/**
* @author James Candan <james@codejourneymen.com>
* @copyright 2015 Acme
* @license http://www.php.net/license/3_01.txt PHP License 3.01
. . .
* @param string $val a value required for the class
* @return void
*/
Example
<?php
/**
* A simple class
*
* This is the long description for this class,
* which can span as many lines as needed. It is
* not required, whereas the short description is
* necessary.
*
* It can also span multiple paragraphs if the
* description merits that much verbiage.
*
* @author Jason Lengstorf <jason.lengstorf@ennuidesign.com>
* @copyright 2010 Ennui Design
* @license http://www.php.net/license/3_01.txt PHP License 3.01
*/
class SimpleClass
{
/**
* A public variable
*
* @var string stores data for the class
*/
public $foo;
/**
* Sets $foo to a new value upon class instantiation
*
* @param string $val a value required for the class
* @return void
*/
public function __construct($val)
{
$this->foo = $val;
}
/**
* Multiplies two integers
*
* Accepts a pair of integers and returns the
* product of the two.
*
* @param int $bat a number to be multiplied
* @param int $baz a number to be multiplied
* @return int the product of the two parameters
*/
public function bar($bat, $baz)
{
return $bat * $baz;
}
}
?>
Namespacing in PHP | Tuts+
OCT 1, 2012 / ELIAS ZERROUQ
http://code.tutsplus.com/tutorials/namespacing-in-php--net-27203
BONUS CONTENT
Namespacing is used to avoid conflicting definitions and introduce more flexibility and organization in your code base.
A namespace definition
<?php
/**
* @file my_project.php
*/
namespace MyProject {
// Regular PHP code goes here, anything goes!
function run()
{
echo 'Running from a namespace!';
}
}
<?php
require 'my_project.php';
\MyProject\run(); // --> success!
run(); // --> Fatal error:
// Call to undefined function run()
<?php
/**
* @file myproject/database/connection.php
*/
namespace MyProject\Database
class Connection {
// Handling database connections
}
<?php
namespace MyProject\Blog\Auth\Handler\Social;
class Twitter {
// Handles Twitter authentication
}
<?php
/**
* @file
* Given two Linkedin contacts, we want to
* update their job title and age.
*/
/**
* @param $person
* @param $newjob
* @return mixed a modified person
*/
function changeJob($person, $newjob) {
$person['job'] = $newjob; // Change job
return $person;
}
/**
* @param $person
* @return mixed a modified person
*/
function happyBirthday($person) {
++$person['age']; // Add 1 to age
return $person;
}
/**
* Let's create two person arrays, each
* containing a bit of info about the person.
*/
$person1 = array(
'name' => 'Tom',
'job' => 'Button-Pusher',
'age' => 34
);
$person2 = array(
'name' => 'John',
'job' => 'Lever-Puller',
'age' => 41
);
/**
* Output the starting values for the people
*/
echo "<pre>P1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>P2: ", print_r($person2, TRUE), "</pre>";
/**
* Tom got a promotion and had a birthday
*/
$person1 = changeJob($person1, 'Box-Mover');
$person1 = happyBirthday($person1);
/**
* John just had a birthday
*/
$person2 = happyBirthday($person2);
/**
* Output the new values for the people
*/
echo "<pre>P1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>P2: ", print_r($person2, TRUE), "</pre>";
?>
<?php
/**
* @file
* Given two Linkedin contacts, we want to
* update their job title and age.
*/
class Person
{
private $_name;
private $_job;
private $_age;
public function __construct($name, $job, $age) {
$this->_name = $name;
$this->_job = $job;
$this->_age = $age;
}
/**
* Set person's job title.
*
* @param $newjob
*/
public function changeJob($newjob) {
$this->_job = $newjob;
}
/**
* Increment person's age.
*/
public function happyBirthday() {
++$this->_age;
}
}
/**
* Let's create two person arrays, each
* containing a bit of info about the person.
*/
$person1 = new Person("Tom", "Button-Pusher", 34);
$person2 = new Person("John", "Lever Puller", 41);
/**
* Output the starting values for the people
*/
echo "<pre>P1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>P2: ", print_r($person2, TRUE), "</pre>";
/**
* Tom got a promotion and had a birthday
*/
$person1->changeJob("Box-Mover");
$person1->happyBirthday();
/**
* John just had a birthday
*/
$person2->happyBirthday();
/**
* Output the new values for the people
*/
echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
?>