The essentials of Object Oriented PHP
The essentials of Object Oriented PHP
Learn, practice, and apply
About the Book
Why learn object-oriented PHP?
Over 80% of websites are now written in PHP, making it more important than ever for web developers to master this programming skill. Although the basics of PHP are easy to learn, it is the knowledge of object-oriented PHP that separates the professionals from the hobbyists.
When using object-oriented programming, we organize the code in an efficient way, so it is easier to work with, develop and upgrade. Due to its many benefits, developers who master the craft of object-oriented PHP are a hot commodity in the job market among companies and enterprises that have a need for advanced online applications.
But this does not tell the full story. Consider the following facts :
- Procedural programming is inefficient
- PHP libraries are written in object-oriented PHP
- PHP frameworks, like Laravel, Symfony, CodeIgniter and Yii rely on object-oriented code
- Drupal and other CMS systems are now object-oriented
- There are more and more parts of WordPress becoming object-oriented
Let's expand on the first fact as it is the most important one - everything else flows from it, i.e. object-oriented programming is gaining popularity because it is more efficient. There are great applications written in the procedural style of PHP, but even the best end up in spaghetti code where functions and variables are mixed together. Add in HTML, CSS and JavaScript to the mix and the code becomes something that is, well, inefficient.
Object-oriented code is more organized. Distinct units are created for a single purpose. This means it is easier to find things in the code. It is also easier to add, replace or remove parts of code as it only has to be done once.
Finally, object-oriented programming gives the opportunity to developers to integrate code libraries from other resources. This is done without worrying about name collisions, even though some of the functions in the code might have the same name.
So, back to the original question, why bother learning object-oriented PHP?
The answer is:
- It is increasingly common
- Developers with this skill earn more. In fact, the knowledge of object-oriented PHP is a prerequisite for getting a job in the PHP world
- The code they write is better as it is less messy and doesn't repeat it self
- The code can be easily expanded with modern libraries that come from the thriving PHP community
With all of its benefits, programming in object-oriented PHP requires a different way of thinking. For this reason it is important to get an understanding of the fundamentals.
What does the book cover?
This book covers the fundamentals of programming in object-oriented PHP. It starts with the basics of writing in an object-oriented style. That style applies to everything including classes, objects, methods and properties. It also covers how code in a class can be approached from within the class and, crucially, from outside it.
The book also shows developers how to write streaming code that is easier to digest and understand because it more closely resembles human language. Plus the book covers a number of the essential skills for learning object-oriented programming. This includes:
- Protecting code inside classes from the outside
- Object inheritance and how it reduces repetition, therefore saving time
- Abstracting classes and methods so that code is organized better
- Constructing applications using interfaces and polymorphism
- The intimidating concept of dependency injection in a practical and easy-to-understand way
The book also covers the most valuable skill of integrating code and code libraries from other sources with the help of namespaces and Composer. Once you finish learning this skill, programming in PHP becomes much faster.
Who is this book for?
Obviously, this book is for procedural PHP developers who want to improve their skills and take their development skills to a new level. It is also for programmers who have a very basic understanding of object-oriented PHP, but who want to learn it properly and get more practice.
Others who will benefit are those programmers who have a background in other object-oriented languages like C++ and Java.
So, in summary, the book is for existing developers who want to learn object-oriented PHP.
Getting the most from this book
As already established, this book is designed for existing developers who want to expand their skill set with object-oriented PHP. As a result it is written in a learn-then-practice form.
Every principle, idea or process is described in a simple and concise way. It is easy to read as the language is simple and the code examples are very basic. This simplicity is done on purpose so the learner can get a good grasp of the essentials of the language without being confused with unnecessary complicted language and code. But don't let this simplicity fool you because it is meant to assimilate in you the essentials of object-oriented PHP, some of them sophisticated and advanced, in the easiest way possible.
The material is accompanied by relevant and elucidating code examples for improved understanding.
Once the foundations are laid, the learner gets a plethora of opportunities to practice and bring the material to life. In the practice opportunities, the reader is guided through the process of writing code examples that are based on what he has just learned. This practice is where proper understanding develops as the learner repeatedly gets a chance to actively assimilate what he has just learned.
It is not a passive learning tool. This book is designed to give developers knowledge and skills in object-oriented PHP quickly. That is achieved through active learning where programmers think for themselves while reading the explanations and examples and practicing the material.
So, to get the most from this book, approach it with an open mind and be ready to get involved. By doing this you will get a good understanding of object-oriented PHP with sufficient knowledge and confidence to apply it practically in your work.
Table of Contents
-
Introduction
- Why bother learning object oriented PHP?
- The purpose of this book
- What does the book cover?
- Who is this book for?
- Getting the most from this book
-
How to create classes and objects?
- How to create classes?
- How to add properties to a class?
- How to create objects from a class?
- Objects, what are they good for?
- How to get an object’s properties?
- How to set an object property?
- How to add methods to a class?
- Conclusion
- Let’s practice what we have just learned
-
The $this keyword
- The $this keyword
- Conclusion
- Let’s practice what we have just learned
-
Chaining methods and properties
- Conclusion
- Let’s practice what we have just learned
-
Access modifiers: public vs. private
- The public access modifier
- The private access modifier
- How to access a private property?
- Why do we need access modifiers?
- Conclusion
- Let’s practice what we have just learned
-
Magic methods and constants unveiled
- The __construct() magic method
- How to write a constructor method without risking an error?
- Magic constants
- Conclusion
- Let’s practice what we have just learned
-
Inheritance in object oriented programming
- How can a class inherit the code of another class?
- How can a child class have its own methods and properties?
- The protected access control modifier
- How to override the parent’s properties and methods in the child class?
- How to prevent the child class from overriding the parent’s methods?
- Conclusion
- Let’s practice what we have just learned
-
Abstract classes and methods
- How to declare classes and methods as abstract?
- Can we have non abstract methods inside an abstract class?
- How to create child classes from an abstract class?
- Conclusion
- Let’s practice what we have just learned
-
Interfaces - the next level of abstraction
- How to declare and implement an interface?
- Can we implement more than one interface in the same class?
- What are the differences between abstract classes and interfaces?
- Conclusion
- Let’s practice what we have just learned
-
Polymorphism in PHP
- How to implement the polymorphism principle?
- Conclusion
- Let’s practice what we have just learned
-
Type hinting
- How to do array type hinting?
- How to do object type hinting?
- Does PHP support type hinting to basic data types?
- Conclusion
- Let’s practice what we have just learned
-
Type hinting for interfaces
- Why type hinting for objects may not be sufficient?
- Type hinting for interfaces
- Conclusion
- Let’s practice what we’ve just learned
-
Static methods and properties
- How to define methods and properties as static?
- How to approach static methods and properties?
- How to approach the static methods from within the class?
- When to use static properties and methods?
- Why static should be used with caution?
- Conclusion
- Let’s practice what we have just learned
-
Traits and code inclusion
- How do traits work?
- Is it possible for a class to use more than one trait?
- How is a trait different from inheritance?
- What are the advantages of using traits?
- What are the disadvantages of using traits?
- In which scenarios is it preferable to use traits?
- Conclusion
- Let’s practice what we have just learned
-
Namespaces and code integration
- The directory structure
- How to define a namespace?
- How to use a class that belongs to a namespace?
- How to alias a class from a namespace with a friendly name?
- How to call a class from the global namespace?
- Can more than one namespace be imported into the same file?
- Conclusion
- Let’s Practice what we have just learned
- Appendix: Group use declarations in PHP7
-
Dependency injection
- The problem: tight coupling between classes
- The solution: dependency injection
- Why is it a good idea to type hint the injected objects?
- Conclusion
- Let’s practice what we have just learned
-
What are exceptions and how to handle them?
- How to throw an exception?
- How to catch an exception?
- Are there any other methods that can help us handle exceptions?
- What about writing the exceptions to a log file?
- When to use exception handling?
- Conclusion
- Let’s practice what we’ve just learned:
-
PDO - PHP database extension
- How to connect with the MySQL database through PDO?
- How to use PDO to insert data into the database?
- How to use PDO to read from the database?
- How to use PDO to update the database?
- How to delete records?
- How to close the database connection?
- Conclusion
- Let’s practice what we have just learned
- supplementary section
-
How to use Packagist and Composer to integrate existing code libraries into your PHP apps?
- How to install composer?
- Installing the package
- How to add packages?
- How to update the packages?
- How to remove a package from Composer?
- Conclusion
-
How to autoload PHP classes the Composer way?
- A short reminder about autoloading Packagist code libraries
- How to directly autoload classes with Composer?
- How to autoload the PSR-4 way?
- How to autoload if the directory structure is complex?
- Conclusion
-
MVC and code organization
- The model
- The broader context - MVC
- The data flow in the MVC pattern
- The simplest MVC example - retrieving the data from the data source
- The simplest MVC example (part 2) - getting data from the user
- Conclusion
-
Epilogue
- What have we learned?
- Some additional resources to advance your knowledge
- Chapter 1 solutions
- Chapter 2 solutions
- Chapter 3 solutions
- Chapter 4 solutions
- Chapter 5 solutions
- Chapter 6 solutions
- Chapter 7 solutions
- Chapter 8 solutions
- Chapter 9 solutions
- Chapter 10 solutions
- Chapter 11 solutions
- Chapter 12 solutions
- Chapter 13 solutions
- Chapter 14 solutions
- Chapter 15 solutions
- Chapter 16 solutions
- Chapter 17 solutions
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earned$12,046,757writing, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Talking with Tech Leads
Patrick KuaA book for Tech Leads, from Tech Leads. Discover how more than 35 Tech Leads find the delicate balance between the technical and non-technical worlds. Discover the challenges a Tech Lead faces and how to overcome them. You may be surprised by the lessons they have to share.The Rails 7 Way
Obie Fernandez, Lucas Dohmen, and Tom Henrik AadlandThe Rails™ 7 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. It illuminates the entire Rails 7 API, its most powerful idioms, design approaches, and libraries. Building on the previous editions, this edition has been heavily refactored and updated.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
JavaScript for hackers
Gareth HeyesLearn how to find interesting behaviour and flaws in JavaScript. Reading this book you will find the latest and greatest techniques for hacking JavaScript and generating XSS payloads. Includes ways to construct JavaScript using only +[]()! characters. Never heard of DOM Clobbering? This book has all the details.
Functional Event-Driven Architecture
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way. Learn to design and develop distributed systems that scale. Identify common design patterns in such systems.
Take your functional programming skills to the next level by joining me in developing a distributed system powered by Apache Pulsar and Fs2 streams, all in Scala 3!
Build Your Own Redis with C/C++
build-your-own.org- Why build Redis? Two topics to learn: network programming and data structures.
- Why from scratch? A quote from Richard Feynman: "What I cannot create, I do not understand".
- Why C? C is widely used for system programming and infrastructure software.
- Why a book? The real Redis is complex, this book breaks down the essense into easy-to-digest steps.
Machine Learning Q and AI
Sebastian Raschka, PhDHave you recently completed a machine learning or deep learning course and wondered what to learn next? With 30 questions and answers on key concepts in machine learning and AI, this book provides bite-sized bits of knowledge for your journey to becoming a machine learning expert.
Implementing DDD, CQRS and Event Sourcing
Alex LawrenceLearn how to implement DDD, CQRS and Event Sourcing. Understand the theory and put it into practice with JavaScript and Node.js. Utilize an extensive source code bundle and an interactive execution feature for a hands-on experience.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #5
1500 QUIZ COMMENTATI (3 libri)
3 Books
Tre libri dei QUIZ MMG Commentati al prezzo di DUE! I QUIZ dei concorsi ufficiali di Medicina Generale relativi agli anni: 2000-2001-2003-2012-2013-2014-2015-2016-2017-2018-2019-2020-2021 +100 inediti Raccolti in unico bundle per aiutarvi nello studio e nella preparazione al concorso. All'interno di ogni libro i quiz sono stati suddivisi per... - #6
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #9
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity... - #10
Mastering Containers
2 Books
Docker and Kubernetes are taking the world by storm! These books will get you up-to-speed fast! Docker Deep Dive is over 400 pages long, and covers all objectives on the Docker Certified Associate exam.The Kubernetes Book includes everything you need to get up and running with Kubernetes!