Post

PHP Object Orientated Programming Cheatsheet

Object-Oriented Programming (OOP) in PHP for WordPress themes involves structuring your code around objects and classes. Instead of relying solely on procedural programming, where functions are executed one after another, OOP emphasizes the creation of reusable and modular components known as objects.

Benefits of coding WordPress themes in Object-Oriented Programming include:

  1. Modularity and Reusability: OOP promotes modular design, allowing you to create classes that encapsulate specific functionality. These classes can be reused across different parts of your theme or even in other projects, enhancing code modularity.

  2. Code Organization: OOP encourages a more organized code structure by grouping related functions and properties into classes. This makes it easier to understand, maintain, and extend your codebase.

  3. Encapsulation: With OOP, you can encapsulate data and behavior within classes, controlling access to properties and methods. This encapsulation enhances code security and reduces the chances of unintended interference with your code.

  4. Inheritance: OOP allows for the creation of classes that inherit properties and methods from other classes. In the context of WordPress themes, this means you can create a base theme class with common functionality and then extend it for specific theme variations.

  5. Polymorphism: OOP enables polymorphism, allowing different classes to implement the same methods with different behaviors. This flexibility is beneficial when adapting your theme to various requirements.

  6. Easier Maintenance: OOP code tends to be more maintainable and extensible. If you need to make changes or add features to your theme, the modular structure allows you to focus on specific classes without affecting the entire codebase.

  7. Testing and Debugging: OOP facilitates unit testing, as you can test individual classes independently. This can lead to more reliable and easier-to-debug code.

  8. WordPress Core Integration: As WordPress itself increasingly adopts object-oriented principles, coding your themes in an object-oriented manner aligns with the direction of the WordPress ecosystem, providing better compatibility and integration.

Here’s a simple example of an OOP approach in a WordPress theme:

1
2
3
4
5
6
7
8
9
10
11
12
class CustomTheme {
    public function __construct() {
        // Theme initialization code
        add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));
    }

    public function enqueue_styles() {
        // Enqueue theme styles
    }
}

$custom_theme = new CustomTheme();

In this example, CustomTheme is a class representing your theme, and the enqueue_styles method encapsulates the logic for enqueuing styles. This structure enhances code organization and encapsulation.

Reasons to use OOP

  1. Avoid spagetti code
  2. Reusable code

class vs object

  • the class is the blueprint
  • the object is the building
  • the class defines the object properties like its dimensions and color it also has functions/methods that do stuff like “open door”
  • You can make many building from the one class

Constructors

  • A contructor is a function that will run automatically when you instantiate an object
  • The contructor can take params and because the contructor will run automatically you can pass values into the constructor
  • Use the this keyword to access properties and methods within the class

Destructors

  • Destructors are used for clean up.
  • Closing connections to databases
  • Destructors run when no other reference to certain object

properties

just like varibles

1
2
3
4
5
6
7
8
class Calendar {
   public $name;
   }

$calendar = new Calendar();
$calendar->name = "Year Planner";

Constants

CLASS contant

the CLASS constant will give you the name of the class that you are in CLASS must be placed inside a function

methods / functions

public functions

You can access these anywhere

Private functions

you can only access from inside the class

protected functions

You can access it from within the class aswell as from any class that extends it its “safer” to not access properties directly. So what you want to do is use a magic __get method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

class User {

    //properties (attributes)
    protected $name;
    protected $age;
    public function __construct($name, $age) {
    	echo 'what ' . __CLASS__  . 'am i in?';
    	$this->name = $name;
    	$this->age = $age;
    }

    //methods (functions)
    public function sayHello(){
    	return 'hello';
    }

    //use the this keyword to retrieve the name from the class
    public function sayGoodbye(){
    	return $this->name .'says goodbye';
    }

    //getter
    public function __get($property) {
    	if(property_exists($this, $property)) {
    		return $this->$property;
    	}
    }

    //setter
    public function __set($property, $value) {
    	if(property_exists($this, $property)) {
    		return $this->$property = $value;
    	}
    	return $this;
    }

}

class Customer extends User {

    //properties
    private $balance;

    public function __construct($name, $age, $balance) {
    	//get the name and the age from the constructor in the parent class
    	parent::__construct($name, $age);
    	$this->balance = $balance;
    }

    //methods
    public function pay($amount) {
    	return $this->name . ' paid $' . $amount;
    }

}

$customer1 = new Customer('dans', 33, 400);
echo $customer1->pay(500);

//create the new user
$user1 = new User('dan', '37');

//access and echo the name property
echo $user1->name;
echo $user1->age;
//class Customer extends User { }
//access and run the sayHello method
//echo $user1->sayHello();
$user1->**set('age', 41);
echo $user1->**get('age');

//get_object_vars will create and array out of an objects properties

$myObj = new class1;
$arr = get_object_vars($myObj);
	foreach($arr as $key=>$val) {
		echo $key | $val;
	}

more info

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.