PHP has been an Object Oriented Language since PHP 5. It’s mature, powerful, and there should be no reason for anyone to hate on it any longer. In this article, I go over the differences between objects and classes, do a short introduction to object oriented programming concepts, and create a small introductory class showing class properties, methods, and local variables.

Classes vs Objects

Imagine that you’re constructing a building. Usually the architect, you as a programmer, will develop a blueprint, the class, and from that blueprint, a building will be constructed, the object. When you create a class, you’re developing the schematics. When the program runs, it looks at those schematics (the class) and constructs the object (instantiates the object).

  • Architect = Programmer
  • Blueprint = Class
  • Building = Object
  • Instantiate = Convert from Class to Object

What we’re doing with a program most of the time is mirroring real-world things. The object that’s constructed from a class doesn’t have to be non-living; we can model living organisms or any idea that can represent an object. Thinking about an animal, like a Dog, we can say that a dog has characteristics, such as: breed, height, length, fur color, etc. We don’t have to just model characteristics of the Dog; we can also model actions that the Dog can perform, such as: barking, walking, drooling, etc. We’ll look at the Dog example in the next few articles, but right now let’s take a look at the class structure.

Class Structure

The class will start with the keyword class and is followed by the Class Name. All characteristics (properties) and actions (methods) will go in between the curly braces.

<?php

	class ClassName {
	    // Properties
	    // Methods
	}

	?>

The property starts off with the visibility modifier,_ public, private, _or protected, followed by the property name. We’ll be looking at visibility modifiers in a later article. Property names can be initialized or set later on. Data types can be specified as of PHP 7.4, such as string, int, etc. If you’re familiar with programming languages like Java, you’ve been exposed to data structures. Explicitly stating data types is a relatively new concept for the PHP world. We’ll discuss that topic in a later article as well.

<?php

	class ClassName {

	  public $property_name = "";        // initialized to empty string
	  private $property_name_2 = "Dino"; // initialized to string
	  protected $property_name_3 = 19;   // initialized to int

	  public $property_name_4;           // not initialized
	}

	?>

#web-development #php #computer-science #programming #software-development

PHP 7.x — P43: Objects and Classes Intro
1.10 GEEK