Object-Oriented PHP & PHP Coding Tutorial for Beginners

This is one among elegant Object-Oriented PHP tutorials that will enable you to learn object oriented PHP in very easy manner. This Object-Oriented PHP for beginners in coming section of this post will focus on PHP programming, Object-Oriented PHP, PHP Object-Oriented programming and various PHP coding tutorial too in order to make you more benefited.

Understanding Object-Oriented Programming

Object-Oriented programming is considered as a coding style which enables the web-developers to congregate identical tasks into classes. However, it lets you to buoy up the code through “don’t repeat yourself” (DRY) principle and is very affable to cultivate.

One most significant and worthy feature of DRY programming is that when a fragment of information alters in your program, generally one change is supposed to upgrade the code. However, one of the major illusion for developers is cultivating the code while data is supposed to be declared most often, which stands for any modification being implemented to the program become more frustrating as they investigate for duplicate data and functionality.

As, OOP is introduces various new syntax and at a glance supposed to be more confounded in contrast of simple procedural or inline code, thus threatens to most of the developers.

Comprehending Objects and Classes

Prior to indulge in nitty gritty insight of the OOP’s finer points, it is necessary to comprehend the fundamental differences between objects and classes. However, this section will take you through building blocks of classes, concerned distinct abilities as well as their uses.

Recognizing the Differences Between Objects and Classes

Lets know the difference between objects and classes with reference to this illustration. A class is something identical to a blueprint for a house. It determine the shape and planning of the house on paper through establishing a link amongst distinct sections of the house defined and planned clearly, even though no existence of the house.

An object is like the actual house built in accordance of that blueprint. However, the stored data in object is like wires, wood and concrete which construct the house. Furthermore, it’s just a aggregation of stuff, if not assembled properly according to the blue print. Thus, when amassed together, results in a useful and organized house.

Classes form data structure and action as well as employ information for Objects building.

In the mean time by identical class, independent multiple object can be created where no object will interfere others. However, following our analogy of construction. It seems to similar to the procedural to built an entire subdivision in accordance of the same blueprint. Where, 150 distinct houses convey same structure and look but comprises distinct families and inside decorations.

Structuring Classes

The syntax of creating a class is very simple and easy; just declare a class in account of class keyword, followed by class name and curly braces {}sets.

1

2

3

4

5

6

7

8

&lt;?php

classMyClass

{

// Class properties and methods go here

}

?&gt;

After accomplishing this, you can assign a new class and save in a variable through employing a new keyword:

1

$obj=newMyClass;

Now, in order to view the contents of the class, you can employ var_damp():

1

var_dump($obj);

Test this process by incorporating these code snippet in a new file called test.php at your local folder.

1

2

3

4

5

6

7

8

&lt;?php

classMyClass

{

// Class properties and methods go here

}

$obj=newMyClass;

var_dump($obj);

?&gt;

Now, you are required to upload this page to your browser at http://localhost/test.php and eventually something will appear should be like this:

1

object(MyClass)#1 (0) { }

With this, you have successfully accomplished your first Object-Oriented PHP script.

Defining Class Properties

Class-specific variables or class, properties are used to add data. However, likewise other regular variable it also works except those who are bound to the object and hence can be accessed only by employing the object. In order to add a property to MyClass, you are required to put the following snippet code to your script:

1

2

3

4

5

6

7

8

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

}

$obj=newMyClass;

var_dump($obj);

?&gt;

Where, the keyword public defines the property visibility, about which you will know later in coming next section. Next, through standard variable syntax a name to the property is assigned as well as a value too. (though class properties don’t require initial value).

In context to read this property and final output to browser, you are supposed to reference the object by property you wish to read.

1

echo$obj-&gt;prop1;

Where the arrow (→) is known as an OOP construct which used to access the method and contained properties assigned to a given object. Moreover, it is possible that multiple instances of a class may exist. So, when an individual object wouldn’t be referenced then the script can’t determine the object to read from.

Therefore, you are required to alter the script in test.php test file in order to read property instead of dumping the entire class through changing the code as listed below.

1

2

3

4

5

6

7

8

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

}

$obj=newMyClass;

echo$obj-&gt;prop1;// Output the property

?&gt;

After reloading your browser you will get following outputs:

I’m a class property!

Defining Class Methods

One most significant amongst class-specific functions is Methods. An object which is capable to perform an individual actions is falls under the class as methods. As for example, in order to create methods which can be set and fetch value of the class property $prop1, include below provided snippet to your code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

$obj=newMyClass;

echo$obj-&gt;prop1;

?&gt;

Here is a noticeable point that by using $this OOP winks object to referenced themselves. While you are supposed to work within a method, you should employ $this likewise same way as you would employ the name of object outside the class.

However, in context of applying these methods, likewise other common regular function call them also, but first of all you are required to reference the concerned object. Now, modify the value after reading the property from MyClass and then read it again after implementing the alteration below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

$obj=newMyClass;

echo$obj-&gt;getProperty();// Get the property value

$obj-&gt;setProperty("I'm a new property value!");// Set a new one

echo$obj-&gt;getProperty();// Read it out again to show the change

?&gt;

After reloading the browser you will get the following:

I’m a class property!
I’m a new property value!

In the case of applying multiple instances of the same class the power of OOP renders to more apparent.

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

// Create two objects

$obj=newMyClass;

$obj2=newMyClass;

// Get the value of $prop1 from both objects

echo$obj-&gt;getProperty();

echo$obj2-&gt;getProperty();

// Set new values for both objects

$obj-&gt;setProperty("I'm a new property value!");

$obj2-&gt;setProperty("I belong to the second instance!");

// Output both objects' $prop1 value

echo$obj-&gt;getProperty();

echo$obj2-&gt;getProperty();

?&gt;

When you will load this result to your browser, it will read as says below:

I’m a class property!
I’m a class property!
I’m a new property value!
I belong to the second instance!

However, you can see here that OOP conveys asunder entities to objects, which tends them to separate easily from distinct snippet of code into small and respective bundles.

Magic Methods in OOP

Towards the endeavor of easier employment, PHP also offer various magic methods or called as special methods which are useful to employ in the case when some specific common actions hit within the objects. Thus, it enables the web-developers to pursue quantity of worthy actions with relative comfort.

Employing Constructors and Destructors

PHP offers a magic method called _construct() which is very helpful when a new object come into existence it called it automatically. Towards clarifying the concept of constructors, include a constructor to MyClass which results in output a message when it designate that a new class has been created:

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

// Create a new object

$obj=newMyClass;

// Get the value of $prop1

echo$obj-&gt;getProperty();

// Output a message at the end of the file

echo"End of file.&lt;br /&gt;";

?&gt;

Note: __CLASS_ says the class name where it is called, however, this is the things known as a magic constant. There are lot of magic constants available that can be read out in the PHP manual.

Following result will appear after reloading the file to your browser:

The class “MyClass” was initiated!
I’m a class property!
End of file.

When an object is destroyed call this function, the _destruct() magic method. It is quite obvious for class cleanup.

It delivers a message when an object is supposed to be destroyed through determining the magic method _destruct() in MyClass:

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

// Create a new object

$obj=newMyClass;

// Get the value of $prop1

echo$obj-&gt;getProperty();

// Output a message at the end of the file

echo"End of file.&lt;br /&gt;";

?&gt;

After determining a destructor, you will got this below assigned result after reloading the test file:

The class “MyClass” was initiated!
I’m a class property!
End of file.
The class “MyClass” was destroyed.

PHP automatically used to unleashed all resources when the end of a file is arrived.

In context to trigger the destructor apparently, by implementing the unset() function you can destroy the object.

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

// Create a new object

$obj=newMyClass;

// Get the value of $prop1

echo$obj-&gt;getProperty();

// Destroy the object

unset($obj);

// Output a message at the end of the file

echo"End of file.&lt;br /&gt;";

?&gt;

After loading to the browser the result changes and appears something like this:

The class “MyClass” was initiated!
I’m a class property!
The class “MyClass” was destroyed.
End of file.

Converting to a String

To check any error when a script try to deliver MyClass as a string, _toString() is an another magic method is implemented.
Attempting to deliver the object as a string without _toString() results in a fatal error. Implement echoto which output the object apart from a magic 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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

// Create a new object

$obj=newMyClass;

// Output the object as a string

echo$obj;

// Destroy the object

unset($obj);

// Output a message at the end of the file

echo"End of file.&lt;br /&gt;";

?&gt;

It shows the following output:

The class “MyClass” was initiated!

Catchable fatal error: Object of class MyClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 40

In order to eliminate this error, you can add a _toString() 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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunction__toString()

{

echo"Using the toString method: ";

return$this-&gt;getProperty();

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

// Create a new object

$obj=newMyClass;

// Output the object as a string

echo$obj;

// Destroy the object

unset($obj);

// Output a message at the end of the file

echo"End of file.&lt;br /&gt;";

?&gt;

While attempting to render the object to a string output in a call to getProperty() method. You can upload the test script to your browser in context of viewing the result:

The class “MyClass” was initiated!
Using the toString method: I’m a class property!
The class “MyClass” was destroyed.
End of file.

Using Class Inheritance

In account of extends keyword classes can easily inherit the properties and methods of another class. For example, in order to create a second class which enhances the MyClass and include a method, you are required to put the following snippet in your test file:

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunction__toString()

{

echo"Using the toString method: ";

return$this-&gt;getProperty();

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

classMyOtherClassextendsMyClass

{

publicfunctionnewMethod()

{

echo"From a new method in ".__CLASS__.".&lt;br /&gt;";

}

}

// Create a new object

$newobj=newMyOtherClass;

// Output the object as a string

echo$newobj-&gt;newMethod();

// Use a method from the parent class

echo$newobj-&gt;getProperty();

?&gt;

Following will be the output, when you will upload it to your browser:

The class “MyClass” was initiated!
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

Overwriting Inherited Properties and Methods

You can modify the functionality of an existing method or property simply by overwriting and declare it again in the new class:

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunction__toString()

{

echo"Using the toString method: ";

return$this-&gt;getProperty();

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

classMyOtherClassextendsMyClass

{

publicfunction__construct()

{

echo"A new constructor in ".__CLASS__.".&lt;br /&gt;";

}

publicfunctionnewMethod()

{

echo"From a new method in ".__CLASS__.".&lt;br /&gt;";

}

}

// Create a new object

$newobj=newMyOtherClass;

// Output the object as a string

echo$newobj-&gt;newMethod();

// Use a method from the parent class

echo$newobj-&gt;getProperty();

?&gt;

It display the output which sits below in your browser:

A new constructor in MyOtherClass.
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

Preserving Original Method Functionality While Overwriting Methods
If you want to include some new functionality to an inherited method even buoying up the implemented original method, you can employ parenkeyword with scope resolution operator (::):

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

&lt;?php

classMyClass

{

public$prop1="I'm a class property!";

publicfunction__construct()

{

echo'The class "',__CLASS__,'" was initiated!&lt;br /&gt;';

}

publicfunction__destruct()

{

echo'The class "',__CLASS__,'" was destroyed.&lt;br /&gt;';

}

publicfunction__toString()

{

echo"Using the toString method: ";

return$this-&gt;getProperty();

}

publicfunctionsetProperty($newval)

{

$this-&gt;prop1=$newval;

}

publicfunctiongetProperty()

{

return$this-&gt;prop1."&lt;br /&gt;";

}

}

classMyOtherClassextendsMyClass

{

publicfunction__construct()

{

parent::__construct();// Call the parent class's constructor

echo"A new constructor in ".__CLASS__.".&lt;br /&gt;";

}

publicfunctionnewMethod()

{

echo"From a new method in ".__CLASS__.".&lt;br /&gt;";

}

}

// Create a new object

$newobj=newMyOtherClass;

// Output the object as a string

echo$newobj-&gt;newMethod();

// Use a method from the parent class

echo$newobj-&gt;getProperty();

?&gt;

It displays result of both the new class’s constructor and parent constructor:

The class “MyClass” was initiated!
A new constructor in MyOtherClass.
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

However, perhaps it will be proved as quite obvious and significant for you. Object-Oriented PHP will literally be easy to read and maintain, portable code that will save you precious time and additional efforts of repeating functions most often.

As a qualified PHP developer, Jason Larue is working with PHPDevelopmentServices to replenish the clients with excellent services at competitive rates. He has years of experience of working as a PHP web developer that truly reflects from the solutions that are delivered to the clients in the form of related projects. His experience has enabled him to emerge as an author who contributes in spreading the information regarding PHP web development through well-written blog posts.

Explore the trendiest & the most captivating techniques of the web world. This is a grand platform where anyone can learn and share the informative concept & useful tips that revolve around the web development.