어떻게 PHP에서 고급 객체 지향 프로그래밍을 작성하는?

OOP PHP

OOP PHP

개요: Object Oriented programming (OOPs) is an important technique regardless of the programming language we use. And hence, PHP is not an exception in this.

In this article we will talk about how to develop advanced object oriented programs in PHP.

소개: PHP is a server side scripting language used to develop web pages. In the recent times PHP is becoming popular because of its simplicity. PHP code can be combined with HTML code. Once the PHP code is executed, the web server sends the resulting content in the form of HTML or images which can be interpreted by the browser. We all know the power and importance of object oriented programming or OOPs. This is a technique which is widely used in the modern programming languages.

Common OOPs concepts used in PHP:

Let us talk about some common object oriented concepts which are used in PHP:

  • Inheritance – Inheritance is the important concept of Object oriented programming used in most common programming language. Inheritance is based on the principle of parent and child class. In PHP we achieve inheritance by extending the class. By extending a class the child class inherits the properties of the parent class and additionally we can have few more properties. Let us consider the following sample code –

Listing 1 – Sample code to show inheritance

[Code]

class Employee {

public $firstName = “”;

public $lastName = “”;

public $eCode = “”;

public $dept = “”;

 

public function dailyCommonTask() {

// Code for routine job

}

}

class Accountant extends Employee {

public function processMonthlySalary($eCode) {

// Code for processing salary

}

}

[/Code]

In the above code snippet we see that the class Accountant is extending the Employee class. An accountant is an employee first, so he performs the daily common jobs as other employees do. At the same time, it is the Accountant’s job to process the salary of other employees.

  • Public, Private and Protected – As in any object oriented language, PHP also has the concept of Public, Private and Protected access modifiers. Below mentioned is the feature of these three –
    • Public – With having public access the code is visible and can be modified by any code from anywhere.
    • Private – With having private access the code is visible and can be modified from within the class only.
    • Protected – With having protected access the code is visible and can be modified from the same class or any of its child class.
  • Overloading – Overloading feature enables us to have two methods with same name but with different parameters. Let us see the following code snippet –

Listing 2 – Sample code to show overloading

[Code]

class Accountant extends Employee {

public function processMonthlySalary($eCode) {

// Code for processing salary

}

public function processMonthlySalary($eCode, $variablePayFlag, $variablePercentage) {

면($variablePayFlag) {

echo “Please process the salary with variable pay “;

} 그밖에 {

echo ” Please process the salary without variable pay “;

}

}

}

[/Code]

In the above code, we have two methods having the same name – ‘processMonthlySalary’. In an organization, not all the employees will have the variable pay component in their salary. Hence the accountant will have to process the salary using two different approaches –

  • With variable pay
  • Without variable pay

While processing the salary with variable pay, the accountant needs to mention the amount of the variable pay component.

In the above example, we have explained the general concept of method overloading. But during actual implementation, we need a PHP function called func_get_args () to handle multiple method signature (having same method name) with different arguments. The func_get_args () 모든 인자를 보유 PHP 함수 내부에서 사용,,en,배열로서,,en,그것으로 통과,,en,그래서 같은 기능은 다른 인수로 호출 할 수 있습니다,,en,우리가 myTestFunction라는 함수를 보자,,en,우리는 오버로드 된 함수로 사용하려면,,en,기능 myTestFunction,,en,이 함수를 여러 번 호출은 다음과 같이 될 수있다,,en,요구 사항에 따라 사용할 수있는 모든 인수를해야합니다,,en,첫 번째 호출은 인수를 전달하지 않습니다,,en,두 번째 전화는 하나 개의 인자를 전달 세번째는 두 인자를 보낸다,,en,그래서 함수는 오버로드 기능 역할,,en,myTestFunction,,en,소중한,,en,__call 사용하여 PHP에 과부하를 구현하는 또 다른 방법이있다,,en,및 __callStatic,,en,아래의 스 니펫 코드는 메소드 이름과 함께 그것으로 전달 된 인수를 보여줍니다,,en,여기에 $ 이름은 대소 문자를 구분,,en (as an array) passed into it. So the same function can be called with different arguments.

For example, let us take a function called myTestFunction () and we want to use it as an overloaded function.

[코드]

function myTestFunction()

{

print_r(func_get_args());

}

[/코드]

Now, multiple calls to this function could be as shown below. The func_get_args () will have all the arguments which can be used as per requirement. The first call does not pass any argument, the second call passes one argument and the third one sends two arguments. So the function is acting as an overloaded function.

[코드]

myTestFunction ();

myTestFunction (“안녕하세요”);

myTestFunction (“안녕하세요”,”Dear”);

[/코드]

There is also another way of implementing overloading in PHP by using __call() and __callStatic() methods.

For example, the code snippet below shows the arguments passed into it along with the method name. Here $name is case sensitive. 출력은 메소드 이름을 인쇄하고 인수는에 전달,,en,공공 기능 __call,,en,우리는 개체 컨텍스트에서 호출 '$ 이름,,en,내파하다,,en,공공 정적 기능 __callStatic,,en,우리는 정적 컨텍스트에서 호출 '$ 이름,,en,접근 자와 변경자 -,,en,일반적으로 getter 및 setter로 알려진,,en,접근 자와 변경자 널리 모든 프로그래밍 언어에서 사용되는,,en,접근 자 또는 게터는 반환하거나 클래스 수준 변수의 값을 얻기 위해 사용되는 함수입니다,,en,뮤 테이터 또는 족 세트 또는 클래스 레벨 변수의 값을 수정하는 데 사용되는 함수이다,,en,클래스 이러한 유형의 다른 하나의 층으로부터 집단 방식으로 데이터를 전송하는 데 사용되는,,en,정적 변수는 클래스의 인스턴스를 통해 액세스 할 수 없습니다,,en.

[코드]

public function __call($이름, $논쟁)

{

echo “We are calling in object context ‘$name’ ”

. implode(‘, ‘, $논쟁). “\N”;

}

public static function __callStatic($이름, $논쟁)

{

echo “We are calling in static context ‘$name’ ”

. implode(‘, ‘, $논쟁). “\N”;

}

[/코드]

  • Accessors and Mutators – Commonly known as getters and setters, Accessors and Mutators are widely used in every programming language. Accessors or getters are functions which are used to return or get the value of the class level variables. Mutators or setters are functions which are used to set or modify the value of a class level variable. These types of classes are used to transfer the data in a collective way from one layer to another. Let us consider the following example –

Listing 3 – Sample code for Accessors and Mutators

[Code]

class Employee {

public $firstName = “”;

public $lastName = “”;

public $eCode = “”;

public $dept = “”;

public function getfirstName() {

return $this->firstName();

}

public function setfirstName($firstName) {

$this->firstName = $firstName;

}

public function getlastName() {

return $this->lastName();

}

public function setlastName($lastName) {

$this->lastName = $lastName;

}

public function getECode() {

return $this->eCode();

}

public function setECode($eCode) {

$this->eCode = $eCode;

}

public function getDept() {

return $this->dept();

}

public function setDept($dept) {

$this->dept = $dept;

}

}

[/Code]

These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another.

  • Static – Using static keyword for both variable and method is a common practice in object oriented programming. Static means that the variable or the method is available per instance of the class. Static methods or variables are used without creating instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods it must be taken care that the $this variable is not allowed within a static method. Let us see the following example –

Listing 4 – Sample code for static keyword and method

[Code]

class StaticSample {

public static $my_static = ‘Sample Static variable’;

public function staticValue() {

return self::$my_static;

}

public static function aStaticMethod() {

echo “This is the Hello message from static method”;

}

}

class StaticShow extends StaticSample {

public function checkStatic() {

return parent::$my_static;

}

public function checkStaticMethod() {

return parent::$aStaticMethod;

}

}

[/Code]

  • Abstract Class – In PHP, these two features of object oriented programming are used very frequently. Abstract classes which can’t be instantiated rather they can be inherited. The class which inherits an abstract class can also be another abstract class. PHP에서 우리는 키워드를 사용하여 추상 클래스를 만들 수 있습니다 - '추상적',,en,추상 클래스의 샘플 코드,,en,추상 클래스 testParentAbstract,,en,공공 기능 myWrittenFunction,,en,당신 funciton의 몸,,en,클래스 testChildAbstract는 testParentAbstract를 확장,,en,공공 기능 myWrittenFunctioninChild,,en,함수의 몸,,en,우리는 자식 클래스의 인스턴스를 만들 수 있습니다 - testChildAbstract,,en,그러나 우리는 부모 클래스의 인스턴스를 만들 수 없습니다 - testParentAbstract을,,en,우리는 자식 클래스는 부모 클래스를 확장 것을 볼로,,en,우리는 자식 클래스에서 부모 클래스의 속성을 사용할 수 있습니다,,en,우리는 또한 우리의 필요에 따라 우리의 자식 클래스의 추상 메소드를 구현할 수 있습니다,,en,인터페이스 -,,en,객체 지향 프로그래밍에서,,en,인터페이스는 클래스에 몇 가지 방법 세트의 정의의 모음입니다,,en. Let us see the following code snippet –

Listing 5 – Sample code for Abstract Class

[Code]

abstract class testParentAbstract {

public function myWrittenFunction() {

// body of your funciton

}

}

class testChildAbstract extends testParentAbstract {

public function myWrittenFunctioninChild() {

// body of your function

}

}

[/Code]

In the above example, we can create an instance of the child class – testChildAbstract, but we can’t create the instance of the parent class – testParentAbstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need.

  • Interface – In object oriented programming, Interface is a collection of definition of some set of methods in a class. By implementing an interface, 우리는 인터페이스에 정의 된 방법에 따라 클래스를 강제로,,en,인터페이스는 다른 언어와 같이 정의된다,,en,'인터페이스'- 우선 우리는 키워드를 사용하여 인터페이스를 정의해야,,en,우리를 구현하는 동안 단지 구현 클래스에 '구현'키워드를 언급 할 필요가,,en,인터페이스에 대한 코드 샘플,,en,인터페이스 myIface,,en,공공 myFunction 함수,,en,클래스 myImpl는 myIface를 구현,,en,함수 본문,,en,PHP는 웹 애플리케이션 개발을위한 가장 인기있는 언어 중 하나로 떠오르고있다,,en,프로그래밍의 다양한 측면을 지원하는 고급 기능이 향상되었습니다,,en,객체 지향 기능을 이해하고 구현하는 것이 가장 중요하다,,en,우리의 논의에서 우리는 세부 사항에 덮여있다,,en,OOP 모든 프로그래밍 언어에서 거의 사용되는 기술이다,,en. In PHP, interface is defined like any other language. First we need to define the interface using the keyword – ‘interface’. While implementing we just need to mention the ‘implements’ keyword in the implementing class.

Listing 6 – Sample Code for Interface

[Code]

interface myIface {

public function myFunction($이름);

}

class myImpl implements myIface {

public function myFunction($이름) {

// function body

}

}

[/Code]

Summary: PHP has emerged as one of the most popular language for web application development. It has been enhanced with advanced features to support different aspects of programming. Object oriented features are the most important to understand and implement. In our discussion we have covered it in details.
Let us conclude our discussion in the form of following bullets –

  • OOP is a technique which is used almost in all programming languages.
  • In PHP we have all the commonly used object oriented programming concepts as below –
    • Inheritance
    • Overloading
    • Accessors & Mutators
    • Public, Private, Protected, Static
    • Abstract classes and Interfaces

 

 

 

 

Tagged on: ,
============================================= ============================================== 아마존에서 최고의 Techalpine 책을 구입하십시오,en,전기 기술자 CT 밤나무 전기,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share