×


OOPS and PHP

In this section we will look at OOP with PHP . Refering the below explanations prior to interviews will surely help you to answer some of the most common questions an rookie/intermediate level developer might face in interviews.Here is a diagram depicting object oriented programming concepts

oop[1]

CLASSES

In object-oriented programming , a class is a template definition of the method s and variables in a particular kind of object . Thus, an object is a specific instance of a class; it contains real values instead of variables.

A CLASS is a template of an object.An OBJECT  is an instance of class

DATA ABSTRACTION

Concept of Abstraction in PHP is important php oop (object oriented programming) concept.To show the needed/relevant information or details without showing all information which is not necessary is called abstraction.

 

Abstract Classes. – An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

 

 

The constructor of a class defines what happens when you instantiate an object from this class. The destructor of a class defines what happens when you destroy the object instance

Static methods and creating an instance of an Abstract class

The documentation says: “It is not allowed to create an instance of a class that has been defined as abstract.”. It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:

A very simple explanation of the use of abstract class would be to use Abstract class when there is a ‘IS-A’ relationship between classes. For example, Lion is a Animal, Cat is an Animal. So, Animal can be an abstract class with common implementation like no. of legs, tail etc.

Interfaces in PHP

Interfaces resemble  abstract classes in that they include abstract methods that the programmer must define in the classes that inherit from the interface. In this way, interfaces contribute to code organization because they commit the child classes to abstract methods that they should implement.

PHP does not allow multiple inheritance.Interfaces are a compromise. Most of the problems with multiple inheritance don’t apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to “implement” as many of those as they want.

Example:-

 

More than one interfaces can be implemented by a class.For example

 

Interfaces and Abstract classes – a Comparison

Interfaces support multiple inheritance Abstract class wont.Interfaces Does not have a data member while abstract class have.Abstract class can have complete methods and also they can have different access rights While in an interface everything is public.Complete member of an abstract class can be static

POLYMORPHISM

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.

ENCAPSULATION

It is a concept of wrapping up or binding up related data members and methods in a single module known as Encapsulation. Encapsulation refers to a concept where we encapsulate all the data and member functions together to form an object.For example see the below code

 

Here the name,age ,the properties that belongs to a person are encapsulated in to an object Person

INFORMATION HIDING

In programming, the process of hiding details of an object or function.Information hiding is a powerful programming technique because it reduces complexity. One of the chief mechanisms for hiding information is encapsulation — combining elements to create a larger entity.

INHERITANCE

PRIVATE,PUBLIC AND PROTECTED

public scope to make that variable/function available from anywhere, other classes and instances of the object.
private scope when you want your variable/function to be visible in its own class only.
protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.
When you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.Protected methods are not available ij  subclasses

OVERLOADING AND OVERRIDING

Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.

An example of overriding:

Overloading in PHP provides means to dynamically “create” properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

 

Consider the above class in which method run is redeclared .This will throw fatal error as the function cannot be redeclared

I f a class Myprofile extends above class Me then the function can be redeclared inside the Myprofile class.This is called OVERRIDING

Now in the class ‘Me’ the method ‘run’ cannot be redeclared. Also the second declaration has more parameters .Assigning more parameters means we are OVERLOADING the function.To establish OVERLOADING we use a magic function.The magic function is _ __CALL

 

Operator Overloading which allows  operators to act according to the type of data they are using. For example the plus operator (+) can be used on arrays to perform array merging

MAGIC METHODS

The “magic” methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.

__construct(),__destruct,__call(),__set(),__get(),__clone,__toString(),__sleep,__wakeup

are some of the magic methods in php . You may already know and have used some of these in prior examples

TRAITS IN PHP

Trates too help us to tweak our structure to overcome single inheritance problem with PHP

S.O.L.I.D: The First 5 Principles of Object Oriented Design

1 Single-responsibility Principle
2 Open-closed Principle
3 Liskov substitution principle
4 Interface segregation principle
5 Dependency Inversion principle

TYPES OF ERRORS IN PHP

Syntax error – The syntax error occurs if there is a syntax mistake in the script; the output is syntax error. A syntax error stops the execution of the script

Fatal Error: – Fatal errors are caused when PHP understands but can’t be done. Fatal errors stop the execution of the script. If you call ab  undefined function, then the output thrown is a fatal error.

Warnings – Warnings will not stop execution of the script. The main reason for warning error is to include a missing file or using the incorrect number of parameters in a function.

Notice –  Notice is the same as a warning error i.e. in the notice, execution of the script does not stop.

Different types of errors are :

– E_ERROR: A fatal error that causes script termination
– E_WARNING: Run-time warning that does not cause script termination
– E_PARSE: Compile time parse error.
– E_NOTICE: Run time notice caused due to error in code
– E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
– E_CORE_WARNING: Warnings that occur during PHP’s initial startup
– E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
– E_USER_ERROR: User-generated error message.
– E_USER_WARNING: User-generated warning message.
– E_USER_NOTICE: User-generated notice message.
– E_STRICT: Run-time notices.
– E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
– E_ALL: Catches all errors and warnings

NAMESPACES IN PHP

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHPclasses/functions/constants or third-party classes/functions/constants.

Example:-

 

Namespace name definitions

Unqualified name
This is an identifier without a namespace separator, such as Foo
Qualified name
This is an identifier with a namespace separator, such as Foo\Bar
Fully qualified name
This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. The namespace \Foo is also a fully qualified name.
Relative name
This is an identifier starting with namespace, such as namespace\Foo\Bar.
Names are resolved following these resolution rules:

Fully qualified names always resolve to the name without leading namespace separator. For instance \A\Bresolves to A\B.
Relative names always resolve to the name with namespace replaced by the current namespace. If the name occurs in the global namespace, the namespace\ prefix is stripped. For example namespace\A inside namespace X\Y resolves to X\Y\A. The same name inside the global namespace resolves to A.
For qualified names the first segment of the name is translated according to the current class/namespace import table. For example, if the namespace A\B\C is imported as C, the name C\D\E is translated toA\B\C\D\E.
For qualified names, if no import rule applies, the current namespace is prepended to the name. For example, the name C\D\E inside namespace A\B, resolves to A\B\C\D\E.
For unqualified names, the name is translated according to the current import table for the respective symbol type. This means that class-like names are translated according to the class/namespace import table, function names according to the function import table and constants according to the constant import table. For example, after use A\B\C; a usage such as new C() resolves to the name A\B\C(). Similarly, after use function A\B\fn; a usage such as fn() resolves to the name A\B\fn.
For unqualified names, if no import rule applies and the name refers to a class-like symbol, the current namespace is prepended. For example new C() inside namespace A\B resolves to name A\B\C.
For unqualified names, if no import rule applies and the name refers to a function or constant and the code is outside the global namespace, the name is resolved at runtime. Assuming the code is in namespace A\B, here is how a call to function foo() is resolved:
It looks for a function from the current namespace: A\B\foo().
It tries to find and call the global function foo().

COMMON FUNCTIONS IN PHP

sizeof($array)
Use this function to find out how many elements an array contains
array_values($array)
Use this function to retrieve all the values from an associative array.
array_keys($array)
Use this function to retrieve all the keys from an associative array.
array_pop($array)
Use this function to remove an element from the end of an array.
array_push($array, $value)
// This function adds an element to the end of an array.
array_shift($array)
This function removes an element from the beginning of an array.
array_unshift($array, $value)
This function adds an element to the beginning of an array.
array_map($callback, $array1)
This function returns an array containing all the elements of array1after applying the callback function to each one. You can pass more than one array. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
sort($array)
// This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order. Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
array_reverse($array)
// This function reverses the order of elements in an array.
array_merge($array)
Use this function when you need to combine data from two or more arrays into a single structure
array_rand($array)
This function selects one or more random elements from an array.
array_search($search, $array)
This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.
array_slice($array, $offset, $length)
Use this function to break a larger array into smaller ones.
array_unique($array)
Use this function when you need to remove non-unique elements from an array
extract($array)
Import variables into the current symbol table from an array. For Better understanding read the doc about this function. It is very nice. Its opposite is compact().
array_key_exists($key, $array)
This functions returns TRUE if the given key is set in the array.
in_array($searched_value, $array)
This functions returns TRUE if the given value exists in the array
The most commonly used Functions for manipulating Strings in PHP.

substr()
This function returns the part of the string as an output.
strlen()
This function returns the length of the string
trim()
This function removes the white-spaces from both start and the end of the string.
ltrim()
This function removes the white-spaces from the left part of the string.
rtrim()
This function removes the white-spaces from the right part of the string.
strtolower()
This function converts the string to lower case
strtoupper()
This function converts the string to upper case
str_replace()
The str_replace() function replaces some characters with some other characters in a string.
explode()

This function breaks the string into array on the basis of delimiter passed

 

One Comment

  • root May 31, 2018 at 8:27 pm

    HI please refer for more tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *