Skip to content

Instantly share code, notes, and snippets.

@conleec
Created December 16, 2017 16:05
Show Gist options
  • Save conleec/6893ec41690757fe228bcf6d03b05e9a to your computer and use it in GitHub Desktop.
Save conleec/6893ec41690757fe228bcf6d03b05e9a to your computer and use it in GitHub Desktop.
PHP - Object Oriented Notes
@conleec
Copy link
Author

conleec commented Dec 16, 2017

Encapsulation

Getters and Setters explained along with property and method visibility.
https://goo.gl/cQ71rF

Inheritance

DRY = Don't Reuse Your code...

	class Model {

		protected $dates = [];

		public function __get($property) {
			// TODO: Implement __get() method.

			if (in_array($property, $this->dates)) {
				return new DateTime($this->{$property});
			}
			return $this->{$property};
		}
	}

	class User extends Model {

		protected $dates = ['createdOn'];

		protected $createdOn = '2017-12-12 12:50:00';

		protected $testString = "This is a test.";
	}

	class Comment extends Model {

		protected $dates = ['createdOn'];

		protected $createdOn = '2017-12-12 12:50:00';
	}

	$user = new User();

	var_dump($user->createdOn);

This example takes any method that contains "createdOn" and returns a DateTime() object. All other methods get passed thru.

Autoloading

A way of automatically loading PHP classes when they're called, so we don't need a gazillion "includes"

https://getcomposer.org/

Package for doing autoloads. Codecourse has tutorial on using it.

Traits

A way to share methods with classes

Exceptions

You can create a new exception class, which extends standard PHP exception. This allows custom functionality and messages when a specific exception is thrown.

	class GatewayPaymentFailedException extends Exception {
		// custom error handling
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment