php oop object oriented programming for beginners project

Object-Oriented PHP for Beginners

For many PHP programmers, object-oriented programming is a frightening concept, full of complicated syntax and other roadblocks. As detailed in my book, Pro PHP and jQuery, you’ll learn the concepts behind object-oriented programming (OOP), a style of coding in which related actions are grouped into classes to aid in creating more-compact, effective code.

To see what you can do with object-oriented PHP, take a look at the huge range of PHP scripts on CodeCanyon, such as this SQLite Object-Oriented Framework.

Or, if you’re struggling with the do-it-yourself approach, you could hire a professional on Envato Studio either to fix errors for you or to create full PHP applications and modules.

php oop object oriented programming for beginners project. Смотреть фото php oop object oriented programming for beginners project. Смотреть картинку php oop object oriented programming for beginners project. Картинка про php oop object oriented programming for beginners project. Фото php oop object oriented programming for beginners projectphp oop object oriented programming for beginners project. Смотреть фото php oop object oriented programming for beginners project. Смотреть картинку php oop object oriented programming for beginners project. Картинка про php oop object oriented programming for beginners project. Фото php oop object oriented programming for beginners projectphp oop object oriented programming for beginners project. Смотреть фото php oop object oriented programming for beginners project. Смотреть картинку php oop object oriented programming for beginners project. Картинка про php oop object oriented programming for beginners project. Фото php oop object oriented programming for beginners project

Understanding Object-Oriented Programming

Object-oriented programming is a style of coding that allows developers to group similar tasks into classes. This helps keep code following the tenet «don’t repeat yourself» (DRY) and easy-to-maintain.

«Object-oriented programming is a style of coding that allows developers to group similar tasks into classes

One of the major benefits of DRY programming is that, if a piece of information changes in your program, usually only one change is required to update the code. One of the biggest nightmares for developers is maintaining code where data is declared over and over again, meaning any changes to the program become an infinitely more frustrating game of Where’s Waldo? as they hunt for duplicated data and functionality.

OOP is intimidating to a lot of developers because it introduces new syntax and, at a glance, appears to be far more complex than simple procedural, or inline, code. However, upon closer inspection, OOP is actually a very straightforward and ultimately simpler approach to programming.

Understanding Objects and 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. This section will go over the building blocks of classes, their different capabilities, and some of their uses.

Recognizing the Differences Between Objects and Classes

Developers start talking about objects and classes, and they appear to be interchangeable terms. This is not the case, however.

Right off the bat, there’s confusion in OOP: seasoned developers start talking about objects and classes, and they appear to be interchangeable terms. This is not the case, however, though the difference can be tough to wrap your head around at first.

A class, for example, is like a blueprint for a house. It defines the shape of the house on paper, with relationships between the different parts of the house clearly defined and planned out, even though the house doesn’t exist.

An object, then, is like the actual house built according to that blueprint. The data stored in the object is like the wood, wires, and concrete that compose the house: without being assembled according to the blueprint, it’s just a pile of stuff. However, when it all comes together, it becomes an organized, useful house.

Classes form the structure of data and actions and use that information to build objects. More than one object can be built from the same class at the same time, each one independent of the others. Continuing with our construction analogy, it’s similar to the way an entire subdivision can be built from the same blueprint: 150 different houses that all look the same but have different
families and decorations inside.

Structuring Classes

The syntax to create a class is pretty straightforward: declare a class using the class keyword, followed by the name of the class and a set of curly braces ( <> ):

After creating the class, a new class can be instantiated and stored in a variable using the new keyword:

To see the contents of the class, use var_dump() :

Try out this process by putting all the preceding code in a new file called test.php in [your local] testing folder:

Load the page in your browser at http://localhost/test.php and the following should display:

In its simplest form, you’ve just completed your first OOP script.

Defining Class Properties

To add data to a class, properties, or class-specific variables, are used. These work exactly like regular variables, except they’re bound to the object and therefore can only be accessed using the object.

The keyword public determines the visibility of the property, which you’ll learn about a little later in this chapter. Next, the property is named using standard variable syntax, and a value is assigned (though class properties do not need an initial value).

To read this property and output it to the browser, reference the object from which to read and the property to be read:

Modify the script in test.php to read out the property rather than dumping the whole class by modifying the code as shown:

Reloading your browser now outputs the following:

Defining Class Methods

Methods are class-specific functions. Individual actions that an object will be able to perform are defined within the class as methods.

Reload your browser, and you’ll see the following:

«The power of OOP becomes apparent when using multiple instances of the
same class.»

When you load the results in your browser, they read as follows:

As you can see, OOP keeps objects as separate entities, which makes for easy separation of different pieces of code into small, related bundles.

Magic Methods in OOP

To make the use of objects easier, PHP also provides a number of magic methods, or special methods that are called when certain common actions occur within objects. This allows developers to perform a number of useful tasks with relative ease.

Using Constructors and Destructors

For the purpose of illustrating the concept of constructors, add a constructor to MyClass that will output a message whenever a new instance of the class is created:

Note — __CLASS__ returns the name of the class in which it is called; this is what is known as a magic constant. There are several available magic constants, which you can read more about in the PHP manual.

Reloading the file in your browser will produce the following result:

To call a function when the object is destroyed, the __destruct() magic method is available. This is useful for class cleanup (closing a database connection, for instance).

Output a message when the object is destroyed by defining the magic method
__destruct() in MyClass :

With a destructor defined, reloading the test file results in the following output:

«When the end of a file is reached, PHP automatically releases all resources.»

To explicitly trigger the destructor, you can destroy the object using the
function unset() :

Now the result changes to the following when loaded in your browser:

Converting to a String

This results in the following:

To avoid this error, add a __toString() method:

In this case, attempting to convert the object to a string results in a call to the getProperty() method. Load the test script in your browser to see the result:

Tip — In addition to the magic methods discussed in this section, several others are available. For a complete list of magic methods, see the PHP manual page.

Using Class Inheritance

Classes can inherit the methods and properties of another class using the extends keyword. For instance, to create a second class that extends MyClass and adds a method, you would add the following to your test file:

Upon reloading the test file in your browser, the following is output:

Overwriting Inherited Properties and Methods

To change the behavior of an existing property or method in the new class, you can simply overwrite it by declaring it again in the new class:

This changes the output in the browser to:

Preserving Original Method Functionality While Overwriting Methods

To add new functionality to an inherited method while keeping the original method intact, use the parent keyword with the scope resolution operator ( :: ):

This outputs the result of both the parent constructor and the new class’s constructor:

Assigning the Visibility of Properties and Methods

«For added control over objects, methods and properties are assigned visibility.»

Note — Visibility is a new feature as of PHP 5. For information on OOP compatibility with PHP 4, see the PHP manual page.

Public Properties and Methods

All the methods and properties you’ve used so far have been public. This means that they can be accessed anywhere, both within the class and externally.

Protected Properties and Methods

Declare the getProperty() method as protected in MyClass and try to access it directly from outside the class:

Upon attempting to run this script, the following error shows up:

Now, create a new method in MyOtherClass to call the getProperty() method:

This generates the desired result:

Private Properties and Methods

A property or method declared private is 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.

Reload your browser, and the following error appears:

Static Properties and Methods

A method or property declared static can be accessed without first instantiating the class; you simply supply the class name, scope resolution operator, and the property or method name.

«One of the major benefits to using static properties is that they keep their stored values for the duration of the script.»

When you load this script in your browser, the following is output:

Commenting with DocBlocks

«The DocBlock commenting style is a widely
accepted method of documenting classes.»

While not an official part of OOP, the DocBlock commenting style is a widely accepted method of documenting classes. Aside from providing a standard for
developers to use when writing code, it has also been adopted by many of the most popular software development kits (SDKs), such as Eclipse and NetBeans, and will be used to generate code hints.

A DocBlock is defined by using a block comment that starts with an additional asterisk:

The real power of DocBlocks comes with the ability to use tags, which start with an at symbol ( @ ) immediately followed by the tag name and the value of the tag. DocBlock tags allow developers to define authors of a file, the license for a class, the property or method information, and other useful information.

The most common tags used follow:

A sample class commented with DocBlocks might look like this:

Once you scan the preceding class, the benefits of DocBlock are apparent: everything is clearly defined so that the next developer can pick up the code and never have to wonder what a snippet of code does or what it should contain.

Comparing Object-Oriented and Procedural Code

There’s not really a right and wrong way to write code. That being said, this section outlines a strong argument for adopting an object-oriented approach in software development, especially in large applications.

Reason 1: Ease of Implementation

«While it may be daunting at first, OOP actually provides an easier approach to dealing with data.»

While it may be daunting at first, OOP actually provides an easier approach to dealing with data. Because an object can store data internally, variables don’t need to be passed from function to function to work properly.

Also, because multiple instances of the same class can exist simultaneously, dealing with large data sets is infinitely easier. For instance, imagine you have two people’s information being processed in a file. They need names, occupations, and ages.

The Procedural Approach

Here’s the procedural approach to our example:

When executed, the code outputs the following:

While this code isn’t necessarily bad, there’s a lot to keep in mind while coding. The array of the affected person’s attributes must be passed and returned from each function call, which leaves margin for error.

To clean up this example, it would be desirable to leave as few things up to the developer as possible. Only absolutely essential information for the current operation should need to be passed to the functions.

This is where OOP steps in and helps you clean things up.

The OOP Approach

Here’s the OOP approach to our example:

This outputs the following in the browser:

There’s a little bit more setup involved to make the approach object oriented, but after the class is defined, creating and modifying people is a breeze; a person’s information does not need to be passed or returned from methods, and only absolutely essential information is passed to each method.

«OOP will significantly reduce your workload if implemented properly.»

On the small scale, this difference may not seem like much, but as your applications grow in size, OOP will significantly reduce your workload if implemented properly.

TipNot everything needs to be object oriented. A quick function that handles something small in one place inside the application does not necessarily need to be wrapped in a class. Use your best judgment when deciding between object-oriented and procedural approaches.

Reason 2: Better Organization

Another benefit of OOP is how well it lends itself to being easily packaged and cataloged. Each class can generally be kept in its own separate file, and if a uniform naming convention is used, accessing the classes is extremely simple.

Assume you’ve got an application with 150 classes that are called dynamically through a controller file at the root of your application filesystem. All 150 classes follow the naming convention class.classname.inc.php and reside in the inc folder of your application.

The controller can implement PHP’s __autoload() function to dynamically pull in only the classes it needs as they are called, rather than including all 150 in the controller file just in case or coming up with some clever way of including the files in your own code:

Having each class in a separate file also makes code more portable and easier to reuse in new applications without a bunch of copying and pasting.

Reason 3: Easier Maintenance

Due to the more compact nature of OOP when done correctly, changes in the code are usually much easier to spot and make than in a long spaghetti code procedural implementation.

If a particular array of information gains a new attribute, a procedural piece of software may require (in a worst-case scenario) that the new attribute be added to each function that uses the array.

An OOP application could potentially be updated as easily adding the new property and then adding the methods that deal with said property.

A lot of the benefits covered in this section are the product of OOP in combination with DRY programming practices. It is definitely possible to create easy-to-maintain procedural code that doesn’t cause nightmares, and it is equally possible to create awful object-oriented code. [Pro PHP and jQuery] will attempt to demonstrate a combination of good coding habits in conjunction with OOP to generate clean code that’s easy to read and maintain.

Summary

At this point, you should feel comfortable with the object-oriented programming style. Learning OOP is a great way to take your programming to that next level. When implemented properly, OOP will help you produce easy-to-read, easy-to-maintain, portable code that will save you (and the developers who work with you) hours of extra work. Are you stuck on something that wasn’t covered in this article? Are you already using OOP and have some tips for beginners? Share them in the comments!

And if you want to purchase affordable, high-quality PHP scripts, you can find thousands of them on CodeCanyon.

Author’s Note — This tutorial was an excerpt from Pro PHP and jQuery (Apress, 2010).

Источник

PHP OOP: Object Oriented Programming for beginners + Project

php oop object oriented programming for beginners project. Смотреть фото php oop object oriented programming for beginners project. Смотреть картинку php oop object oriented programming for beginners project. Картинка про php oop object oriented programming for beginners project. Фото php oop object oriented programming for beginners project

English | MP4 | AVC 1280×720 | AAC 48KHz 2ch | 18.5 Hours | 2.34 GB

PHP OOP: Learn OOP PHP and Take your skills to another level. Make serious money by building awesome applications.

This course will guaranteed you success if you apply yourself, and take the time to learn everything included.

PHP has allowed me to make a really great income, so much that It gives me time to teach others about it. You too can become a professional in the field, and create the life you always dreamed of.

PHP is one of the best web programming languages in the world, and all the big important websites, like Google, Apple, Facebook, Yahoo, Wikipedia and many more, use it for their web applications.

Getting Started
1 Section Overview
2 Edwin from the future
3 Code Editors I recommend (Optional Lecture)
4 Web Development Software Installation (XAMPP)
5 Course Exercise files
6 Displaying errors in PHP

OOP Fundamentals
7 Section Overview
8 Referencing Parent Class with Static
9 Constructors and Destructors
10 Defining a class
11 Defining methods
12 Instantiating a Class
13 Defining properties
14 Class Inheritance
15 Access Control Modifiers
16 Static Modifier
17 Getters and Setters

OOP Project – Building a Photo Gallery System
18 Overview of this project
19 Project Directories & Assets
20 Editing and Modifying Files
21 Gallery System Links
22 Creating Pages
23 Creating Database and User Table

Database Class
24 Section Overview
25 Testing Query Method
26 Improving our Connection to be more OOP
27 Setting Up the Database Connection
28 Initializing all Includes in one file
29 Init file inclusion reminder (Edwin from the future)
30 Creating the Database Class
31 Future Update for database class
32 Automatic DB Connection Setup
33 The Query Method
34 Database Class Helper Methods

The User Class
35 Section Overview
36 Short Way Auto Instantiation
37 Creating The Attribute Finder Method
38 Adding our Instantiation Method
39 Using our Instantiation Method to find all users
40 Using our Instantiation Method to find 1 User
41 Undeclared Object Backup Function
42 Updating the Autoload Function (Edwin from the future)
43 So what is going on
44 Creating our User Class
45 Testing our find all method
46 Static Method Usage and Challenge
47 Creating a Find user id method and Solution
48 Create This Query Method
49 Assigning Array Values to Object Properties
50 Auto Instantiation Method
51 Testing the Instantiation Method

The Session Class
52 Section Overview
53 Duplicate return = Important watch the whole lecture – Edwin from the future
54 Login page position – (Edwin from the future)
55 Login Form Creation Download
56 Creating our Login out Feature
57 Creating message method
58 Outputting Feedback for User
59 Starting Sessions
60 The Checking login Method
61 The Login Method
62 The Logout Method
63 Controlling Access to Admin
64 Creating The Login Page
65 Creating the Verify Method Part 1
66 Creating the Verify Method part 2

Files Basics
67 Section Overview
68 Understanding File Permissions
69 Magic Constants

Uploading Files
70 Section Overview
71 Configuring PHP for File Uploads
72 Sending Files
73 Analyzing Uploaded File Structure
74 File Error Code Explained
75 Moving Uploaded Files

CRUD Create Method
76 Section Overview
77 Create Method Query Part1
78 Create Method Query Part 2
79 Inserting Last ID Method (Challenge)
80 Testing our Method (Solution)

CRUD Update Method
81 Update Method Query
82 Testing our Update Method

CRUD Delete Method
83 Delete Method
84 Testing the Delete Method

Abstracting and Improving
85 Section Overview
86 Testing the Abstracted Update Method
87 Escaping Values From our Abstracted Methods
88 Improving the Create Method
89 Abstracting Tables
90 Abstracting Properties
91 Abstracting the Create Method Part 1
92 Abstracting the Create Method Part 2
93 Modifying the properties method
94 Testing the Abstracted Create Method
95 Abstracting the Update Method

The Photo Class
96 Section Overview
97 Setting Up our Properties Array
98 Building Directory Paths
99 Set File Method
100 Save Method Part # 1
101 Save Method Part # 2
102 HTML Form Creation
103 Uploading and Testing
104 Coding The HTML for our Photos Table
105 Coding The PHP for a Photo Table
106 Dynamic Image Path
107 Creating the Database Table for our Photo Class
108 Abstracting the remaining methods
109 Create the Parent Class
110 Fixing lecture 90 Double Return
111 Late Static Binding
112 Coding The Photo Class
113 Adding Class Properties
114 Testing Inherited Methods

ADMIN PHOTOS Deletion Section
115 Section Overview
116 DELETE PAGE and Links Part # 1
117 DELETE Page Part # 1
118 Making our Application More Generic
119 Creating The Delete Method
120 Setting Up The Right Redirect Paths for Delete

ADMIN PHOTOS Edit Photo Section
121 Section Overview
122 Setting Size for Photos Page Thumbnail
123 Creating The Edit Page
124 Creating The Edit Page Part #2
125 Writing our PHP Code Part # 1
126 Writing our PHP Code Part # 2
127 Displaying Data
128 Updating Data
129 Picture and Sidebar Styling
130 Installing The Text Editor

ADMIN USERS
131 Section Overview
132 Creating The User Edit Page
133 Updating User
134 Empty Password Field Fix
135 Updating User Modification
136 Delete within Edit User Page
137 Fixing Duplicate Record Creation Bug
138 Displaying User Page
139 Working with User Image
140 Creating User Image Column in DB Table
141 Deleting Users
142 Creating Add User Page Part # 1
143 Creating Add User Page Part # 2 Testing
144 Assigning POST values to Object Properties
145 Setting Up Image Upload for User

ADMIN COMMENTS
146 Section Overview
147 Displaying & Making Comments – FRONT-END
148 Displaying & Making Comments – BACK-END
149 Deleting Comments
150 Creating the Individual Comment Page Part # 1
151 Creating the Individual Comment Page Part # 2
152 Creating the Count Comment Code and CHALLENGE
153 Comment Count Link & SOLUTION
154 Deleting Specific Photo Comments Code
155 Creating the Comments Table in the Database
156 Creating the Comment Class
157 Self Instantiation Comment Method
158 Find Comments Method
159 Testing our Comment Form
160 Including Our Classes in Photo.php FRONT-END
161 Pulling Data From Form Part # 1
162 Pulling Data From Form Part #2

ADMIN Dashboard Setup
163 Section Overview
164 Dynamic Menu to Photo.php
165 Dashboard HTML Snippets Inclusion
166 Adding Google API Charts
167 Tracking Page Views Method
168 Creating the Count All Method and Echoing Photo Count
169 Setting Up Users and Comment Counts
170 Modifying Chart Properties
171 Dynamic Data in Chart Creation

FRONT-END Gallery System
172 Setting Up Index to Display Photos Part # 1
173 Setting Up Index to Display Photos Part # 2
174 Correcting Photos Alignment with CSS
175 Coding the PHP in Photo.php FRON-END
176 Home Page Link and Footer Modifications

FRONT-END PAGINATION
177 Section Overview
178 Creating Previous Link – SOLUTION
179 Paginate Indication and Looping
180 Pagination Indication CSS
181 CLEANING UP
182 Setting Up our Pagination Variables
183 Creating the Paginate CLASS
184 Creating our Construct Function to Initialize some Properties
185 Building our Paginate Class Methods Part # 1
186 Building our Paginate Class Methods Part # 2
187 Instantiating and Testing Paginate
188 Setting Up our Next Page Link
189 Putting our Next Link to Work – CHALLENGE

EXTRA FEATURES
190 Extra Features Overview
191 Testing our AJAX Code
192 Creating the AJAX PHP Method
193 Modifying Improving Our AJAX PHP method
194 Photo Library Sidebar Part #1 – CHALLENGE INCLUDED
195 Photo Library Sidebar Part #2 – SOLUTION INCLUDED
196 Photo Library Sidebar Part #3 – COMPLETED
197 Creating Session Methods for Notifications in the Edit User Page Part # 1
198 Creating Session Methods for Notifications in the Edit User Page Part # 2
199 Updating User Methods
200 Setting Up Notifications for CRUD Part #1
201 Creating the Modal + HTML Snippets Download
202 Setting Up Notifications for CRUD Part #2
203 Installing a Multiple Upload and Drop JS File Plugin Part #1
204 Installing a Multiple Upload and Drop JS File Plugin Part #2
205 Installing a Multiple Upload and Drop JS File Plugin Part #3 – COMPLETE
206 Edit Photo Page Sidebar jQuery Dropdown
207 Login Page CSS
208 Confirm Delete with Javascript and jQuery
209 Conclusion and BONUS
210 Including Modal from somewhere else
211 Pulling Pictures Into Gallery Modal
212 Enable Selection Button on Click – jQuery
213 Enabling the Selection Button with jQuery
214 Pulling User Id with jQuery and Javascript
215 Pulling Image Name with jQuery and Javascript
216 Writing the AJAX – Setting User Image

Taking our application online
217 Hosting setup
218 Displaying errors online
219 Uploading files and database creation
220 Importing database and setting up configurations CHALLENGE
221 Creating an online site root path SOLUTION
222 Testing photos deletion functionality

Extra Lectures
223 Database refactoring
224 Updating photos with user id

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *