Adding Custom Validation Rules in Valitron

Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron uses simple, straightforward validation methods with a focus on readable and concise syntax. Valitron is the simple and pragmatic validation library we’ve been looking for.

Adding Custom Validation Rules :

To add your own validation rule, use the addInstanceRule method with a rule name, a custom callback or closure, and a error message to display in case of an error. The callback provided should return boolean true or false.

such as :

$validation->addInstanceRule(‘functionName’, function () {
return false;

$validation->rule(‘functionName’, ‘fieldName’)->message(‘Error Message’);


We can also use the following structure :

if (condition) {

$validation->addInstanceRule(‘functionName’, function () {
return false;

$validation->rule(‘functionName’, ‘fieldName’)->message(‘Error Message’);




RedBeanPHP (The Power ORM)

RedBeanPHP is an easy to use ORM for PHP. It’s a Zero Config ORM lib that ‘automagically’ builds your database schema.


RedBeanPHP is an easy to use ORM for PHP. It’s a Zero Config ORM lib that ‘automagically’ builds your database schema.

IMPORTANT! RedBeanPHP 3.5 is approaching EOL status!

After 1 October, RedBeanPHP 3.5 will no longer be supported nor maintained !
If you want to continue to use a maintained version of RedBeanPHP, upgrade to version 4.3!
UPDATE: Due to popular demand, support has been extended until December 2016


2016-10-25: RedBeanPHP 4.3.3 has been released !
2016-10-02: RB 3.5 support has been extended until December 2016
2016-05-01: RedBeanPHP 4.3.2 has arrived !
2016-01-09: RedBeanPHP 4.3.1 has been released!
2015-10-01: RedBeanPHP 4.3 has been released!
2015-09-11: RedBeanPHP 4.3 beta 2 has been released!
2015-09-02: RedBeanPHP 4.3 Beta 1 has been released!
2015-07-29: RedBeanPHP 4.2.5 has been released!


Code Example

This is how you do CRUD in RedBeanPHP:

    require 'rb.php';
R::setAutoResolve( TRUE );        //Recommended as of version 4.2
$post = R::dispense( 'post' );
$post->text = 'Hello World';
$id = R::store( $post );          //Create or Update
$post = R::load( ‘post’, $id );   //Retrieve
R::trash( $post );                //Delete

This automatically generates the database, tables and columns… on-the-fly. It infers relations based on naming conventions. RedBeanPHP is written by BDFL Gabor de Mooij and the RedBeanPHP community.

Zero Config

No verbose XML files, no annoying annotations, no YAML or INI. Zero Config. Just start coding.

Fluid Schema

During development, RedBeanPHP will adapt the database schema to fit your needs, giving you the NoSQL experience. When deploying to production servers, you can freeze the schema and benefit from performance gains and referential integrity.
RedBeanPHP offers the best of both worlds!


RedBeanPHP is a compact library yet packed with features: auto-discovery of models, deep copying and smart import features will boost your productivity!
Write less, do more!


RedBeanPHP strives to support all ALL Free, Open Source databases.
Currently, RedBeanPHP supports: MySQL, MariaDB, SQLite, PostgreSQL and CUBRID.


Download the easy-to-use one-in-all package, one single file containing the entire RedBeanPHP library! No composer, no auto-loaders, no configuration, just download and run! Go to the download page and download to latest version of RedBeanPHP!



CRUD stands for Create, Update, Retrieve and Delete. CRUD operations are the core of many web applications.

Working with beans

RedBeanPHP works with beans. Most interactions with the database are accomplished using beans. Beans are used to carry data from and to the database.

Every bean has a type and an ID. The type of a bean tells you which table in the database is used to store the bean. Every type maps to a corresponding table. The ID of a bean is the primary key of the corresponding record.
You can create a new bean by dispensing one.


To create a new bean (of type ‘book’) use:

    $book = R::dispense( 'book' );

You can now add properties:

    $book->title = 'Learn to Program';
$book->rating = 10;

You can also use array notation if you like:

    $book['price'] = 29.99; //you can use array notation as well

and store the bean in the database:

    $id = R::store( $book );

At this point, the bean will be stored in the database and all tables and columns have been created.
The bean will now have an ID, which is also returned for your convenience.

RedBeanPHP will build all the necessary structures to store your data. However custom indexes and constraints have to be added manually (after freezing your web application).


You can dispense any type of bean you like, as long as the type name consists of lowercase alphabetical characters:

    $page = R::dispense('page'); //valid

$page = R::dispense( ‘Page’ ); //invalid: uppercase
$page = R::dispense( ‘cms_page’ ); //invalid: _
$page = R::dispense( ‘@#!’ ); //invalid

However dispense also offers some shortcuts:

    $twoBooks = R::dispense( 'book', 2 );

list($book, $page) = R::dispenseAll( ‘book,page’ );
list($book, $pages) = R::dispenseAll( ‘book,page*2’ );

Properties of beans may contain alphanumeric characters and underscores. Camelcased properties will automatically convert to snake_case:

    $book->isSoldOut = TRUE; //is_sold_out
$book->hasISBNCode = TRUE; //has_isbn_code


To load a bean, simply pass the type and ID of the bean you’re looking for:

    $book = R::load( 'book', $id ); //reloads our book

If the bean does not exist an empty bean with ID 0 will be returned.


To update a bean in the database, add or change properties:

    $book->title = 'Learn to fly';
$book->rating = 'good';
$book->published = '2015-02-15';
R::store( $book );

Note that we added a new property ‘published’, RedBeanPHP will add a new column of type ‘date’ for this property. Also, it will widen the ‘rating’ from INTEGER to VARCHAR to support text as well as numbers.

    //Examples of other data types
$meeting->when = '19:00:00'; //Time
$meeting->when = '1995-12-05'; //Date
$photo->created = '1995-12-05 19:00:00'; //Date time
$meeting->place = '(1,2)'; //SPATIAL only works in postgreSQL
$price->amount = '12.37'; //FIXED POINT NUMERIC - MySQL and Postgres
$price->amount = '$25.00'; //MONEY TYPE - Postgres only

If you want a suitable data type of monetary values, use the ‘XX.XX’ format and you’ll get a fixed precision number data field. To make use of Postgres special purpose, currency-aware money data type, prefix the value with a common currency symbol.

You can use R::isoDate() and R::isoDateTime() to generate the current date(time) if you like.

As of RedBeanPHP 4.1 you can also use spatial columns for MySQL, learn more.

RedBeanPHP will dynamically add new columns to your database. It determines the column type to use by looking at the value you are trying to store. For instance, a short text might be stored as a VARCHAR while a large text might be stored as TEXT. Similarly, a boolean value will probably get stored as TINYINT but when you put a float in that property the column will probably be changed to FLOAT or DOUBLE (depending on your database).
Some column types behave differently, for instance if you store a valid ISO formatted date (i.e. 2015-01-01) RedBeanPHP builds a DATE column, but this column will not change. In general, RedBeanPHP tries to adapt the database to your application. If you’re done developing, you can freeze the database using the freeze() function. After that, the database schema will no longer change (because it is very unlikely you want to store something other than a date in a column you filled with perfectly formatted date in the first place).
Note that RedBeanPHP will never throw away columns or ‘shrink’ columns (from TEXT to VARCHAR) to avoid data loss. RedBeanPHP also only manipulates column types it recognizes, so if you change a VARCHAR(255) to a VARCHAR(254) it will leave that column alone, since it no longer recognizes the type. This means that if you customize columns, RedBeanPHP leaves them alone from that point on.
If RedBeanPHP alters the database in a way you don’t like, don’t worry, you can always tune the schema to your liking (just use your database management tool or phpmyadmin), you can even freeze certain tables only.


To delete a bean:

    R::trash( $book ); //for one bean
R::trashAll( $books ); //for multiple beans

To delete all beans of a certain type:

    R::wipe( 'book' ); //burns all the books!

To destroy the entire database simply invoke the nuclear method (be careful!):



To load a series of beans use:

    $books = R::loadAll( 'book', $ids );


To quickly reload a bean:

    $bean = $bean->fresh();

Finding Beans

Instead of loading beans, you can also use the find() method to search for beans using certain criteria. Learn how to query beans in RedBeanPHP.


If you do not know the ID of a bean, you can search for beans using the find method:

    $book  = R::find( 'book', ' rating > 4 ');

The find() method uses good old SQL. No fancy, custom query language — just plain old SQL.

The find operation in this example returns all beans of type book having a rating of four stars or more.

Find and SQL

The following example demonstrates how to use find() with bindings.

    $books = R::find( 'book', ' title LIKE ? ', [ 'Learn to%' ] );

This find operation will return all beans of type ‘book’ having a title that begins with the phrase: ‘Learn to’.

If find() has no results it will return an empty array.

There is no need to use mysql_real_escape. Always use the bindings.
Never use PHP variables in your query!


To use a ‘SELECT-IN’ style query use the R::genSlots function to generate the correct number of ‘?’ slots:

    $promotions = R::find( 'person',
' contract_id IN ('.R::genSlots( $contractIDs ).')',
$contractIDs );

Find One

If you want a single bean instead of an array, use:

    $book  = R::findOne( 'book', ' title = ? ', [ 'SQL Dreams' ] );

If no beans match the criteria, this function will return NULL.

Find All

Use findAll if you don’t want to add any conditions (but you want to order or limit… )

    $books = R::findAll( 'book' );
$books = R::findAll( 'book' , ' ORDER BY title DESC LIMIT 10 ' );

If no beans match your criteria, this function returns an empty array.

Named slots

All find methods: find, findOne and findAll also accept named slots:

    $books  = R::find( 'book', ' rating < :rating ', [ ':rating' => 2 ] );

Besides querying beans, you can also use regular SQL queries.

Cursors (4.2+)

You can also use find with cursors:

    $collection = R::findCollection( 'page', ' ORDER BY content ASC LIMIT 5 ' );
while( $item = $collection->next() ) {

The advantage of using a cursor is that the entire collection will not be loaded into memory all at once. This is handy for dealing with large bean collections.

Find like (4.2+)

To find a bean matching certain criteria, you can use R::findLike(). The following code returns all flowers that are either yellow OR blue:

    R::findLike( 'flower', [
'color' => ['yellow', 'blue']
], ' ORDER BY color ASC ' );

Note that you can append some SQL here along with bindings.

Find or create (4.2+)

This works like R::findLike() but also creates (and stores) the bean if it does not exist yet…

    $book = R::findOrCreate( 'book', [
'title' => 'my book',
'price' => 50] );

Find Multiple (4.2+)

findMulti() takes a query and turns the result into several bean collections having different types:

    $beans = R::findMulti( 'book,page', '
SELECT book.*, page.* FROM book
INNER JOIN page.book_id =
WHERE book.category = ?
', [ $cat] );

The first parameter of this function lists the types to load, the second parameter is the query, then come the optional query parameter bindings. The result of this operation will be something like:

'book' => book beans...
'page' => page beans...

Besides loading various bean types at once from a query, this method can also restructure them, for instance to ‘put the pages in the book’ use (example of 4th parameter):

'a'       => 'book'
'b'       => 'page'
'matcher' =>  function( $a, $b ) {
return ( $b->book_id == $a->id );
'do'      => function( $a, $b ) {
$a->noLoad()->ownPageList[] = $b;

The fourth parameter of findMulti takes an array containing arrays like the one above. The array in the example tells findMulti how to restructure the pages and the books. First it defines two variables ‘a’ and ‘b’ it then defines a matcher function, telling RedBeanPHP to execute the ‘do’ clause if the book_id of a page matches the id of a page. The ‘do’ clause then puts the page in the pageList of the selected book. While you can specify mappings like this, a better idea might be to write your own set of mapping functions returning structures like this.


Querying the database manually is also possible with RedBeanPHP. You can use the SQL query functions provided by RedBeanPHP. To execute a query:

    R::exec( 'UPDATE page SET title="test" WHERE id = 1' );

To get a multidimensional array:

    R::getAll( 'SELECT * FROM page' );

The result of such a query will be a multidimensional array:

[0] => Array
[id] => 1
[title] => frontpage
[text] => hello

Note that you can use parameter bindings as well:

    R::getAll( 'SELECT * FROM page WHERE title = :title',
[':title' => 'home']

To fetch a single row:

    R::getRow( 'SELECT * FROM page WHERE title LIKE ? LIMIT 1',
[ '%Jazz%' ]

To fetch a single column:

    R::getCol( 'SELECT title FROM page' );

And finally, a single cell

    R::getCell( 'SELECT title FROM page LIMIT 1' );

To get an associative array with a specified key and value column use:

    R::getAssoc( 'SELECT id, title FROM page' );

In this case, the keys will be the IDs and the values will be the titles. getAssocRow will return complete rows.

In my examples, I like to use the short array notation.
In PHP < 5.4 you’ll have to use the classic array notation:

array( ‘key’ => ‘value’ ).

Get the insert ID (4.2+)

To get the ID after an insert in MySQL/MariaDB compatible databases use:

    R::exec( 'INSERT INTO ... ' );
$id = R::getInsertID();

Converting records to beans

You can convert rows to beans using the convertToBeans() function:

    $sql = 'SELECT author.* FROM author
JOIN club WHERE = 7 ';
$rows = R::getAll( $sql );
$authors = R::convertToBeans( 'author', $rows );

As of version 4.3.2 you can also use: R::convertToBean, without the s, for single rows.

There is no need to use mysql_real_escape as long as you use parameter binding.

Besides querying you can also use other database functionality (like transactions) in RedBeanPHP. Learn more about database functions.

How to use queries

Sometimes using a plain query is more efficient than using beans. For instance, consider the following example:

    $books = R::findAll( 'book' );
foreach( $books as $book ) {
echo $book->title;
echo $book->author->name;
foreach( $book->sharedCategoryList as $cat ) {
echo $cat->name;

Using a plain query this task could be accomplished far more efficiently:

    $books = R::getAll( 'SELECT
book.title AS title, AS author,
GROUP_CONCAT( AS categories FROM book
JOIN author ON = book.author_id
LEFT JOIN book_category ON book_category.book_id =
LEFT JOIN category ON book_category.category_id =
' );
foreach( $books as $book ) {
echo $book['title'];
echo $book['author'];
echo $book['categories'];

One of the biggest mistakes people make with ORM tools is to try to accomplish everything with objects (or beans). They forget SQL is a very powerful tool as well. Use SQL if you are merely interested in generating reports or lists.

Slim is a micro framework for PHP

Slim is a micro framework for PHP . We can build quickly powerful web applications and APIs. Slim is a dispatcher that receives an HTTP request, invokes an appropriate callback routine, and returns an HTTP response.

Slim is an ideal tool to create APIs that consume, repurpose, or publish data. Slim is also a great tool for rapid prototyping. Heck, we can even build full-featured web applications with user interfaces. More importantly, Slim is super fast and has very little code. In fact, we can read and understand its source code in only an afternoon!


First, we need a web server like Apache. We should configure our web server  so that it sends all appropriate requests to one “front-controller” PHP file. We instantiate and run our Slim app in this PHP file.

A Slim app contains routes that respond to specific HTTP requests. Each route invokes a callback and returns an HTTP response. To get started, we first instantiate and configure the Slim application. Next, we define our application routes. Finally, we run the Slim application. It’s that easy. Here’s an example application:

// Create and configure Slim app
$config = ['settings' => [
    'addContentLengthHeader' => false,
$app = new \Slim\App($config);

// Define app routes
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->write("Hello " . $args['name']);

// Run app

When we build a Slim app, we are often working directly with Request and Response objects. These objects represent the actual HTTP request received by the web server and the eventual HTTP response returned to the client.

Every Slim app route is given the current Request and Response objects as arguments to its callback routine. These objects implement the popular PSR7  interfaces. The Slim app route can inspect or manipulate these objects as necessary. Ultimately, each Slim app route must return a PSR7  Response object.

Slim is designed to play well with other PHP components, too. We can register additional first-party components  that build upon Slim’s default functionality. It’s also easy to integrate third-party components found on Packagist.

If anyone is new to Slim, I recommend to read this documentation from start to finish. If anyone is already familiar with Slim, she/he can instead jump straight to the appropriate section.

This documentation begins by explaining Slim’s concepts and architecture before venturing into specific topics like request and response handling, routing, and error handling.

Installing slim:
We recommend to install Slim with Composer. Navigate into project’s root directory 
and execute the bash command shown below. This command downloads the Slim Framework and its 
third-party dependencies into your project’s vendor/ directory. 
composer require slim/slim "^3.0"
Require the Composer autoloader into your PHP script, and you are ready to start using Slim.
require 'vendor/autoload.php';

Don’t have Composer? It’s easy to install by following the instructions on their download page.
If one is upgrading from version 2 to version 3, these are the significant changes that need to be aware of.
Slim 3 requires PHP 5.5 or latest version.

New Route Function Signature
$app->get('/', function (Request $req,  Response $res, $args = []) {
    return $res->withStatus(400)->write('Bad Request');

Getting _GET and __POST variables
$app->get('/', function (Request $req,  Response $res, $args = []) {
    $myvar1 = $req->getParam('myvar'); //checks both _GET and _POST [NOT PSR-7 Compliant]
    $myvar2 = $req->getParsedBody()['myvar']; //checks _POST  [IS PSR-7 compliant]
    $myvar3 = $req->getQueryParams()['myvar']; //checks _GET [IS PSR-7 compliant]
Hooks are no longer part of Slim as of v3. You should consider reimplementing any functionality associated with the default hooks in Slim v2 as middleware instead.
If you need the ability to apply custom hooks at arbitrary points in your code (for example, within a route), you should consider a third-party package 
such as Symfony’s EventDispatcher or Zend Framework’s EventManager.

Remova;l HTTP Cache

In Slim v3 we have removed the HTTP-Caching into its own module Slim\Http\Cache.

Removal of Stop/Halt

Slim Core has removed Stop/Halt. In your applications, you should transition to using the withStatus() and withBody() methods.

Removal of autoloader

Slim::registerAutoloader() have been removed, we have fully moved to composer.

Changes to container

$app->container->singleton(...) is now $app['...'] = function () {}; Please read Pimple docs for more info

Removal of configureModel()

$app->configureMode(...) has been removed in v3.


Removal of PrettyExceptions

PrettyExceptions cause lots of issues for many people, so this have been removed.

ROute::setDefaultConditions(…) has been removed

We have switched routers which enable you to keep the default conditions regex inside of the route pattern.

Changes to redirect

In Slim v2.x one would use the helper function $app->redirect(); to trigger a redirect request. In Slim v3.x one can do the same with using the Response class like so.


$app->get('/', function ($req, $res, $args) {
  return $res->withStatus(302)->withHeader('Location', 'your-new-uri');

Middleware Signa

The middleware signature has changed from a class to a function.

New signature:

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $req,  Response $res, callable $next) {
    // Do stuff before passing along
    $newResponse = $next($req, $res);
    // Do stuff after route is rendered
    return $newResponse; // continue

You can still use a class:

namespace My;

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Middleware
    function __invoke(Request $req,  Response $res, callable $next) {
        // Do stuff before passing along
        $newResponse = $next($req, $res);
        // Do stuff after route is rendered
        return $newResponse; // continue

// Register
$app->add(new My\Middleware());
// or

Middleware Execution

Application middleware is executed as Last In First Executed (LIFE).

Flash Message

Flash messages are no longer a part of the Slim v3 core but instead have been moved to seperate Slim Flash package.

In v3.0 cookies has been removed from core. See FIG Cookies for a PSR-7 compatible cookie component.

Removal of Crypto

In v3.0 we have removed the dependency for crypto in core.

New Router

Slim now utilizes FastRoute, a new, more powerful router!

This means that the specification of route patterns has changed with named parameters now in braces and square brackets used for optional segments:

// named parameter:
$app->get('/hello/{name}', /*...*/);

// optional segment:
$app->get('/news[/{year}]', /*...*/);

Route Middleware

The syntax for adding route middleware has changed slightly. In v3.0:


Getting the current route

The route is an attribute of the Request object in v3.0:


When getting the current route in middleware, the value for determineRouteBeforeAppMiddleware must be set to true in the Application configuration, otherwise the getAttribute call returns null.

urlFor() is now pathFor in the router

urlFor() has been renamed pathFor() and can be found in the router object:

$app->get('/', function ($request, $response, $args) {
    $url = $this->router->pathFor('home');
    $response->write("<a href='$url'>Home</a>");
    return $response;

Also, pathFor() is base path aware.

Container and DI  ….. Constractiing

Slim uses Pimple as a Dependency Injection Container.

// index.php
$app = new Slim\App(
    new \Slim\Container(
        include '../config/container.config.php'

// Slim will grab the Home class from the container defined below and execute its index method.
// If the class is not defined in the container Slim will still contruct it and pass the container as the first arugment to the constructor!
$app->get('/', Home::class . ':index');

// In container.config.php
// We are using the SlimTwig here
return [
    'settings' => [
        'viewTemplatesDirectory' => '../templates',
    'twig' => [
        'title' => '',
        'description' => '',
        'author' => ''
    'view' => function ($c) {
        $view = new Twig(
                'cache' => false // '../cache'

        // Instantiate and add Slim specific extension
            new TwigExtension(

        foreach ($c['twig'] as $name => $value) {
            $view->getEnvironment()->addGlobal($name, $value);

        return $view;
    Home::class => function ($c) {
        return new Home($c['view']);

PSR7-7 objects

Request, Response, Uri & UploadFile are immutable.

This means that when you change one of these objects, the old instance is not updated.

// This is WRONG. The change will not pass through.
$app->add(function (Request $request, Response $response, $next) {
    $request->withAttribute('abc', 'def');
    return $next($request, $response);

// This is correct.
$app->add(function (Request $request, Response $response, $next) {
    $request = $request->withAttribute('abc', 'def');
    return $next($request, $response);

Message bodies are streams

// ...
$image = __DIR__ . '/huge_photo.jpg';
$body = new Stream($image);
$response = (new Response())
     ->withStatus(200, 'OK')
     ->withHeader('Content-Type', 'image/jpeg')
     ->withHeader('Content-Length', filesize($image))
// ...

For text:

// ...
$response = (new Response())->getBody()->write('Hello world!')

// Or Slim specific: Not PSR-7 compliant.
$response = (new Response())->write('Hello world!');

The end


PHP Superglobal Variable – $_POST

Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

  • $_SERVER
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE


PHP $_POST is widely used to collect form data after submitting an HTML form with method=”post”. $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on “Submit”, the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:

Example :


<form method="post" action="">
    Name: <input type="text" name="fname">
    <input type="submit" name="btn_submit" value="Submit">

if (isset($_POST['btn_submit'])) {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;


Object Oriented Concepts in PHP

Important terms related to Object Oriented Programming.


Classes are the blueprints for php objects – more on that later. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’. When you create a variable inside a class, it is called a ‘property’.This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.

Define a class in PHP is as follows −

   class Books {
      /* Member variables */
      var $price;
      var $title;
      /* Member functions */
      function setPrice($par){
         $this->price = $par;
      function getPrice(){
         echo $this->price ."<br/>";
      function setTitle($par){
         $this->title = $par;
      function getTitle(){
         echo $this->title ." <br/>";
NOTE: The variable $this is a special variable and it refers to the same object.


An individual instance of the data structure defined by a class. You define a class once and then make many 
objects that belong to it. Objects are also known as instance.

Creating objects in php

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

$physics = new Books;
$maths = new Books;
$chemistry = new Books;

NOTE: Here we have created three objects and these objects are independent of each other and they will have their existence 
separately. Next we will see how to access member function and process member variables.

Member Variables

These are the variables defined inside a class. This data will be invisible to the outside of the 
class and can be accessed via member functions. These variables are called attribute of the object once an object is 

Member Function

These are the function defined inside a class and are used to access object data.
Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.

Following example shows how to set title and prices for the three books by calling member functions.

$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example −


This will produce the following result −

Physics for High School
Advanced Chemistry

  • Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class − A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class − A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
  • Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object.
  • Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.


PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −

class Child extends Parent {
   <definition body>

The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −

  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

Following example inherit Books class and adds more functionality based on the requirement.

class Novel extends Books {
   var $publisher;
   function setPublisher($par){
      $this->publisher = $par;
   function getPublisher(){
      echo $this->publisher. "<br />";

Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return some values.

function getPrice() {
   echo $this->price . "<br/>";
   return $this->price;
function getTitle(){
   echo $this->title . "<br/>";
   return $this->title;

Public Members

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −

  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared

Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private members

By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.

A class member can be made private by using private keyword infront of the member.

class MyClass {
   private $car = "skoda";
   $driver = "SRK";
   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   function myPublicFunction() {
      return("I'm visible!");
   private function myPrivateFunction() {
      return("I'm  not visible outside!");

When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member.

Here is different version of MyClass −

class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   function myPublicFunction() {
      return("I'm visible!");
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");


Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers.

As of PHP5, it is possible to define an interface, like this −

interface Mail {
   public function sendMail();

Then, if another class implemented that interface, like this −

class Report implements Mail {
   // sendMail() Definition goes here


A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.

Declaring one constant is easy, as is done in this version of MyClass −

class MyClass {
   const requiredMargin = 1.7;
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.

In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant’s name does not have a leading $, as variable names do.

Abstract Classes

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this −

When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same visibility.

abstract class MyAbstractClass {
   abstract function myAbstractFunction() {

Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

Try out following example −

   class Foo {
      public static $my_static = 'foo';
      public function staticValue() {
         return self::$my_static;
   print Foo::$my_static . "\n";
   $foo = new Foo();
   print $foo->staticValue() . "\n";

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()


   class BaseClass {
      public function test() {
         echo "BaseClass::test() called<br>";
      final public function moreTesting() {
         echo "BaseClass::moreTesting() called<br>";
   class ChildClass extends BaseClass {
      public function moreTesting() {
         echo "ChildClass::moreTesting() called<br>";

Calling parent constructors

Instead of writing an entirely new constructor for the subclass, let’s write it by calling the parent’s constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here’s a simple example −

class Name {
   var $_firstName;
   var $_lastName;
   function Name($first_name, $last_name) {
      $this->_firstName = $first_name;
      $this->_lastName = $last_name;
   function toString() {
      return($this->_lastName .", " .$this->_firstName);
class NameSub1 extends Name {
   var $_middleInitial;
   function NameSub1($first_name, $middle_initial, $last_name) {
      Name::Name($first_name, $last_name);
      $this->_middleInitial = $middle_initial;
   function toString() {
      return(Name::toString() . " " . $this->_middleInitial);

In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent function that it overrides.

NOTE − A constructor can be defined with the same name as the name of a class. It is defined in above example.