What Is a Class in PHP

What is a class in PHP?

In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.


Imagine a Lock:

namespace MyExample;

class Lock
{
private $isLocked = false;

public function unlock()
{
$this->isLocked = false;
echo 'You unlocked the Lock';
}
public function lock()
{
$this->isLocked = true;
echo 'You locked the Lock';
}
public function isLocked()
{
return $this->isLocked;
}
}

Ignore the namespace, private and public declaration right now.

The Lock class is a blueprint for all the Locks in your application. A Lock can either be locked or unlocked, represented by the property $isLocked. Since it can have only these two states, I use a Boolean (true or false) to indicate which state applies. I can interact with the Lock through it's methods lock and unlock, which will change the state accordingly. The isLocked method will give me the current state of the Lock. Now, when you create an object (also often referred to as an instance) from this blueprint, it will encapsulate unique state, e.g.

$aLock = new Lock; // Create object from the class blueprint
$aLock->unlock(); // You unlocked the Lock
$aLock->lock(); // You locked the Lock

Let's create another lock, also encapsulating it's own state

$anotherLock = new Lock;
$anotherLock->unlock(); // You unlocked the Lock

but because each object/instance encapsulates it's own state, the first lock stays locked

var_dump( $aLock->isLocked() );       // gives Boolean true
var_dump( $anotherLock->isLocked() ); // gives Boolean false

Now the entire reponsibility of keeping a Lock either locked or unlocked is encaspulated within the Lock class. You don't have to rebuilt it each time you want to lock something and if you want to change how a Lock works you can change this in the blueprint of Lock instead of all the classes having a Lock, e.g. a Door:

class Door
{
private $lock;
private $connectsTo;

public function __construct(Lock $lock)
{
$this->lock = $lock;
$this->connectsTo = 'bedroom';
}
public function open()
{
if($this->lock->isLocked()) {
echo 'Cannot open Door. It is locked.';
} else {
echo 'You opened the Door connecting to: ', $this->connectsTo;
}
}
}

Now when you create a Door object you can assign a Lock object to it. Since the Lock object handles all the responsibility of whether something is locked or unlocked, the Door does not have to care about this. In fact any objects that can use a Lock would not have to care, for instance a Chest

class Chest
{
private $lock;
private $loot;

public function __construct(Lock $lock)
{
$this->lock = $lock;
$this->loot = 'Tons of Pieces of Eight';
}
public function getLoot()
{
if($this->lock->isLocked()) {
echo 'Cannot get Loot. The chest is locked.';
} else {
echo 'You looted the chest and got:', $this->loot;
}
}
}

As you can see, the reponsibility of the Chest is different from that of a door. A chest contains loot, while a door separates rooms. You could code the locked or unlocked state into both classes, but with a separate Lock class, you don't have to and can reuse the Lock.

$doorLock = new Lock;
$myDoor = new Door($doorLock);

$chestLock = new Lock;
$myChest new Chest($chestLock);

Chest and Door now have their unique locks. If the lock was a magical lock that can exist in multiple places at the same time, like in Quantum physics, you could assign the same lock to both chest and door, e.g.

$quantumLock = new Lock;
$myDoor = new Door($quantumLock);
$myChest new Chest($quantumLock);

and when you unlock() the $quantumLock, both Door and Chest would be unlocked.

While I admit Quantum Locks are a bad example, it illustrates the concept of sharing of objects instead of rebuilding state and responsibility all over the place. A real world example could be a database object that you pass to classes using the database.

Note that the examples above do not show how to get to the Lock of a Chest or a Door to use the lock() and unlock() methods. I leave this as an exercise for your to work out (or someone else to add).

Also check When to use self over $this? for a more in-depth explanation of Classes and Objects and how to work with them

For some additional resources check

  • http://en.wikipedia.org/wiki/Object-oriented_programming
  • http://www.php.net/manual/en/language.oop5.php
  • http://www.tuxradar.com/practicalphp
  • http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html
  • http://articles.sitepoint.com/article/object-oriented-php

what is ::class php in laravel

Answer:

Using that ::class syntax allows you to declare a class without
passing it as a string. When they update ide's it will help to auto
fill namespaces which can't be done with a string.

Source Information:

Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.

Example #10 Class name resolution

<?php
namespace NS {
class ClassName {
}

echo ClassName::class;
}
?>

The above example will output:

NS\ClassName

Note:

The class name resolution using ::class is a compile time
transformation. That means at the time the class name string is
created no autoloading has happened yet. As a consequence, class names
are expanded even if the class does not exist. No error is issued in
that case.

Source Link :: Php Manual

PHP: What does ::class do?

from PHP doc
"Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes."

<?php
namespace NS {

class ClassName {

}

echo ClassName::class;
}
?>

http://php.net/manual/en/language.oop5.basic.php

When to use a Class vs. Function in PHP

Classes are used for representing data as objects. If you're representing something like a user's data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class).

Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer.

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.

Difference between object and class in PHP?

I assume you have read the manual on basic PHP OOP.

A class is what you use to define the properties, methods and behavior of objects. Objects are the things you create out of a class. Think of a class as a blueprint, and an object as the actual building you build by following the blueprint (class). (Yes, I know the blueprint/building analogy has been done to death.)

// Class
class MyClass {
public $var;

// Constructor
public function __construct($var) {
echo 'Created an object of MyClass';
$this->var = $var;
}

public function show_var() {
echo $this->var;
}
}

// Make an object
$objA = new MyClass('A');

// Call an object method to show the object's property
$objA->show_var();

// Make another object and do the same
$objB = new MyClass('B');
$objB->show_var();

The objects here are distinct (A and B), but they are both objects of the MyClass class. Going back to the blueprint/building analogy, think of it as using the same blueprint to build two different buildings.

Here's another snippet that actually talks about buildings if you need a more literal example:

// Class
class Building {
// Object variables/properties
private $number_of_floors = 5; // Each building has 5 floors
private $color;

// Constructor
public function __construct($paint) {
$this->color = $paint;
}

public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}

// Build a building and paint it red
$bldgA = new Building('red');

// Build another building and paint it blue
$bldgB = new Building('blue');

// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
$bldgB->describe();

Why use classes in php?

Encapsulation: A class is a useful packet containing the code and the relevant data together, isolated from everything else. That makes it easier to move it around without searching for exact variables, without collisions with existing code/data.

Of course classes have other uses but in scripting environments like PHP, I think the biggest advantage is that.

EDIT: I was objected with "inheritance is more powerful than encapsulation" argument. I think that does not apply to scripting and web scenarios and I'll try explain why:

First, a web page's lifetime is a request/response pair and ideally less than a second. The state is usually preserved in external entities (session, cookies, db etc). Since the page's lifetime is very short, possible states in a web page code are less than, say, a fat client. It's almost always small bursts of code running and finishing the work continuously. Arguably a web page is comparable to a console application in terms of simplicity and number of design parameters. Although number of input parameters can be gigabytes in a form, the relation between UI elements and input parameters are limited to screen resolution, a user's overall capability to what he/she can fill in at once. Therefore in majority of cases we have small number of input parameters, meaning smaller number of states. Of course in combinatorial and "mutable" world that's not true but in the case of "typical web applications", internal state is also small, hence making my claim plausible.

The input and output in a web application is mostly the same: Input is query parameters or form data and output is an HTML document. Therefore in its short lifetime the input processing and output production code is similarly shaped and designed for a web page. I am aware that I omitted a big chunk of "business logic" in the picture and I'll get to that. However let's make sure that we have no use of nifty features of OOP like "polymorphism" and "inheritance" in these parts of our code. There are very well known, long studied, practical and non-OOP patterns for that. It would be at least dumb to invent new ways of parsing query parameters using "polymorphism", "visitor pattern" etc.

The data access is also performed by existing libraries and luxuries like "inheritance" or "polymorphism" have no use there. You can still use classes but that would simply be encapsulation. You can't inherit/reuse MySQL code for writing T-SQL or PL/SQL code. You need a complete replacement. Oh maybe your SELECT * FROM table could be "inherited", and think of possibilities, wow.

Now what we have left? Yes, the business logic. We already mentioned that business logic is also short bursts of information processing. There is no persistent business state in PHP code itself. We know that almost all business operations must take less than a second due to The Web's requirements. Therefore the states you can go through, again, is much less than a full fledged application. You have atomic, isolated business operations going on for majority of cases in a typical web application.

Now let's go back to design. We know that our page consists of these parts:

  • Input
  • Business logic
    • Data access
  • Output

We already got input, data, output out of the scope of polymorphism and inheritance. Here is our final picture:

  • Input processing
  • Business logic
    • Data access
  • Output production

Although business logic could be the biggest part of our app, it's still got to be in our one second window in a web application therefore has to be small, aka short lived.

Yes a supercomputer can do a lot in a second but we're still talking in terms of majority, common scenarios. What's common? CRUD is common. That's why Ruby on Rails and Active Record pattern is such a success and gained such a popularity because it increased productivity on one thing: CRUD.

The complexity of a design is proportional to the number of data elements and operations involved. And since we assume that majority of operations are CRUD, we have a fixed number of operations and small number of input parameters, we have a small problem space.

There can be exceptions but for most of the cases a design for a small problem space can't be complex and good at the same time. It's very unlikely that you can use inheritance in a web page's design unless there are vast amount of data points and too much redundance going on behind. I repeat, for most of the cases, it's crude CRUD.

Second, (yes there was a first at the beginning in case you forgot), web app performance is important (if not critical) -remember "one second"- and in a scripting environment it's twice as important.

Object-oriented paradigm relies on a very important low-level mechanism for being useful and performant at the same time: pointer indirection. The ability of a CPU reading pointers and jumping to the address pointed by it with almost no difference than jumping to the address directly. That way we can have a virtual method table used for lookups for correct function call and that way compiler can call object's "some()" method without knowing it's exact type because it's just whatever is in the pointer there, yet it still performs like a crazy horse.

That dream ends in the scripting world. You don't have a CPU natively executing instructions. You have bytecodes produced by PHP compiler and that is interpreted by PHP interpreter. Unlike a CPU, PHP interpreter has to deal with higher level concepts like abstractions, classes, types regardless it's a bytecode. The simple pointer indirection for a CPU is a complex set of operations for PHP. Parsing the operation, understanding the operation, making some sanity checks maybe, and finally performing it with another set of bytecodes.

Therefore the overhead of inheritance in a scripting world is orders of magnitudes slower than in a native environment.

That is acceptable of course, as long as gains are more than losses. And thinking of that the performance loss can be recovered in other ways like upgrading, clustering, it doesn't seem like a problem. That's certainly true and here is my final statement:

For most of the scenarios in web application development, an equally maintainable, equally reusable and possibly more performant design could be achieved without calling upon inheritance/polymorphism, therefore encapsulation is the most common and the greatest benefit in PHP, not inheritance.

Object oriented php class simple example

The way you are calling a php page is good. That is from HTML.

What I think, you are getting this wrong. A class showName to get name from database and enterName to save in database. Well what I suggest that should be a function within one single class.

<?php
class Name
{
public $name;
public function showName()
{
/**
Put your database code here to extract from database.
**/
return($this->name);
}
public function enterName($TName)
{
$this->name = $TName;
/**
Put your database code here.
**/
}
}
?>

In checking.php you can include:

<?php
include_once("name_class.php");
$name = $_POST['name']; //add name attribute to input tag in HTML
$myName = new Name();
$myName->enterName($name); //to save in database/
$name=$myName->showName(); //to retrieve from database.
?>

This way you can achieve this, this is just an overview. It is much more than that.



Related Topics



Leave a reply



Submit