Home  >  Article  >  Backend Development  >  PHP object-oriented programming study notes_PHP tutorial

PHP object-oriented programming study notes_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:15:07721browse

Object-oriented programming is a commonly used method in PHP. This article will introduce the simple method of using PHP object-oriented and some basic knowledge. Friends in need can refer to it.

(OOP) to develop. Object-oriented development has many advantages over process-oriented development:
Simple maintenance Modularity is a feature in object-oriented programming. Entities are represented as classes and classes with the same functionality in the same namespace, we can add a class in a namespace without affecting other members of the namespace.
Extensibility Object-oriented programming inherently supports extensibility. If you have a class with a certain function, you can quickly extend this class and create a class with expanded functions.
Code reuse Since functionality is encapsulated in classes, and classes exist as independent entities, providing a class library is very simple.
It is more suitable for multiple people to cooperate to develop projects, so many large and medium-sized websites now choose to use OOP for development.

Now let me introduce object-oriented programming

Classes, attributes and methods

Definition of class syntax format in PHP:

The code is as follows Copy code
class classname [optional attribute]{
 代码如下 复制代码
class classname [可选属性]{
public $property [=value];… //用public声明一个公共标识 然后给予一个变量 变量也可以赋值
function functionname ( args ){ //类的方法里的成员函数
代码} …
//类的方法(成员函数)
}
public $property [=value];… //Use public to declare a public identifier and then assign it to a variable. Variables can also be assigned values ​​

function functionname (args){ //Member function in class method
Code} …

//Class methods (member functions)

}

Generate object (instantiation of class): $object name=new classname( );
 代码如下 复制代码

class person{
function _ _destruct( )
{ echo "bye bye !“; }
}
$a=new person();

Using the object’s properties


In a class, you can access a special pointer $this. When setting or accessing the variable through an operation in the class, use $this->name to reference.

The code is as follows Copy code
class person{
 代码如下 复制代码
 
class BaseClass{
     public function test(){
          ehco "test";
     }
 
     final public function moreTest(){
          echo "moretest";
     }
}
 
class ChildClass extends BaseClass{
     public function moreTest(){
          echo "moretest";
     }
}
// 产生 Fatal error: Cannot override final method BaseClass::moretest()
function _ _destruct( ) { echo "bye bye !"; } } $a=new person();
1.final final: PHP5 adds a new final keyword. If a method in the parent class is declared final, the subclass cannot override the method; if a class is declared final, it cannot be inherited.
The code is as follows Copy code
class BaseClass{ Public function test(){             ehco "test"; } final public function moreTest(){               echo "moretest"; } } class ChildClass extends BaseClass{ Public function moreTest(){               echo "moretest"; } } // Generate Fatal error: Cannot override final method BaseClass::moretest()

 
2.__toString(建议用PHP5.2或者更高版本)

 代码如下 复制代码
class Person{
 代码如下 复制代码
class Person{
     protected $name;
     protected $email;
    
     public function setName($name){
          $this->name = $name;
     }
 
     public function setEmail($email){
          $this->email = $email;
     }
 
     public function __toString(){
          return "$this->name <$this->email>";
     }
}
$rasums = new Person;
$rasums->setName('test');
$rasums->setEmail('test@qq.com');
print $rasums;
     protected $name;

     protected $email;
    
     public function setName($name){

          $this->name = $name;

     }
 
     public function setEmail($email){
          $this->email = $email;
     }
 
     public function __toString(){

          return "$this->name <$this->email>";
 代码如下 复制代码
interface ChildTest{
     public function childTest();
}
class FathTest implements ChildTest1,ChildTest2{
     public function childTest(){
          echo 1;
     }
     …………
}
     }

}
$rasums = new Person;
$rasums->setName('test');
$rasums->setEmail('test@qq.com');
print $rasums;


 
 代码如下 复制代码
abstract class Database{
     abstract public function connect();
     abstract public function query();
     abstract public function fetch();
     abstract public function close();
}
3.接口和抽象类 接口的作用:你想要保证一个类按照特定的名称、可见性和原型实现一个或多个方法。 接口的要求:      类中全部为抽象方法      抽象方法钱不用加abstract      接口抽象方法属性为public      成员属性必须为常量 例:
 代码如下 复制代码
interface ChildTest{      public function childTest(); } class FathTest implements ChildTest1,ChildTest2{      public function childTest(){           echo 1;      }      ………… }
  抽象的作用: 其实抽象类和接口类有一部分很像,记得在哪里看见这样一句话,抽象类就把类像的部分抽出来,这句看上去很搞笑,其实它说出了抽象类的真理,抽象类的作用 是,当你发现你的很多类里面用很多方法你不断的在重复写,那你就可以考虑使用抽象类了,你可能会说“我不是可以重写一个类每个公共类我个实例化一个这个公 共类,调用相同的方法就可以了”,这里是可以,实际上抽象类做的工作也就是这个,不过他省去了你实例化的这个步骤,让你就像直接调用本类方法一样方便,而 且你还可以重载这个方法。 抽象的要求:      类中至少有一个抽象方法      抽象方法钱必须加abstract 例:
 代码如下 复制代码
abstract class Database{      abstract public function connect();      abstract public function query();      abstract public function fetch();      abstract public function close(); }

Note: Abstract methods cannot be defined as private methods or final methods because they need to be inherited.

4. Pass object reference
php4: All "="'s create a copy
php5: Except for objects, when assigning values ​​to other "="s, a copy is created; while objects are references

5. Clone object
1.
Aggregation class:
Introduction to __call method:
__call is called when client code uses a method that is not defined in the class.
__call() accepts two parameters, one is the method name, and the other is all parameters (including arrays) passed to the method to be called
Any value returned by the __call() method will be returned to the client as if the calling method actually existed
Example:

The code is as follows Copy code
 代码如下 复制代码

class Address{
     protected $city;
     protected $country;

     public function setCity($city){$this->city = $city;}
     public function getCity(){return $this->city;}
     public function setCountry($country){$this->country = $country;}
     public function getCountry(){return $this->country;}
}

class Person{
     protected $name;
     protected $address;
     //浅克隆
     public function __construct(){
          $this->address = new Address;
     }

     public function setName($name){
          $this->name = $name;
     }
     public function getName(){
          return $this->name;
     }

     public function __call($method,$arguments){
          if(method_exists($this->address,$method)){
               return call_user_func_array(array($this->address,$method),$arguments);
          }
     }
     //深克隆
     public function __clone(){
          $this->address = clone $this->address;
     }
}

$test1 = new Person;
$test2 = clone $test1;

$test1->setName('testname1');
$test1->setCity('testcity1');
$test2->setName('testname2');
$test2->setCity('testcity2');

echo $test1->getName().'-'.$test1->getCity()."n";
echo $test2->getName().'-'.$test2->getCity()."n";
//testname1-testcity2
//testname2-testcity2

class Address{       protected $city; protected $country; public function setCity($city){$this->city = $city;} Public function getCity(){return $this->city;} Public function setCountry($country){$this->country = $country;} Public function getCountry(){return $this->country;} } class Person{        protected $name; protected $address; //Shallow clone Public function __construct(){ $this->address = new Address; } public function setName($name){                $this->name = $name; } Public function getName(){              return $this->name; } public function __call($method,$arguments){ If(method_exists($this->address,$method)){                     return call_user_func_array(array($this->address,$method),$arguments);           } } //Deep Clone Public function __clone(){ $this->address = clone $this->address; } } $test1 = new Person; $test2 = clone $test1; $test1->setName('testname1'); $test1->setCity('testcity1'); $test2->setName('testname2'); $test2->setCity('testcity2'); echo $test1->getName().'-'.$test1->getCity()."n"; echo $test2->getName().'-'.$test2->getCity()."n"; //testname1-testcity2 //testname2-testcity2



6. Important attribute access (__set __get __isset __unset) __isset __unset is only useful after 5.1
Function: Intercept the demand for attributes. In order to improve the degree of separation, we must also implement __isset() and __unset(), so that when we use isset to detect attributes or unset() to delete attributes, we can ensure that the behavior of the class is correct
Example:

}
The code is as follows
 代码如下 复制代码

class Person{
     protected $__data = array('email','test');

     public function __get($property){
          if(isset($this->__data[$property])){
               return $this->__data[$property];
          }else{
               return false;
          }
     }

     public function __set($property,$value){
          if(isset($this->__data[$property])){
               return $this->__data[$property] = $value;
          }else{
               return false;
          }
     }
 
     public function __isset($property){
          if(isset($this->__data[$property])){
               return true;
          }else{
               return false;
          }
     }
 
     public function __unset($property){
          if(isset($this->__data[$property])){
               return unset($this->__data[$property]);
          }else{
               return false;
          }
     }
}

$test = new Person;
$test->email= 'test';
var_dump($test->email);

Copy code

class Person{
​​ protected $__data = array('email','test');

public function __get($property){

If(isset($this->__data[$property])){

                    return $this->__data[$property];
            }else{
                    return false;

          }
public function __set($property,$value){ If(isset($this->__data[$property])){

                     return $this->__data[$property] = $value;

            }else{           } } Public function __isset($property){ If(isset($this->__data[$property])){                    return true;             }else{                     return false;           } }
Public function __unset($property){ If(isset($this->__data[$property])){                      return unset($this->__data[$property]);
            }else{
                    return false;           } } } $test = new Person; $test->email= 'test'; var_dump($test->email); Note: These two methods will only capture missing attributes. If you define an attribute for your class, PHP will not call __get() and __set() when accessing this attribute; These two methods completely destroy any idea of ​​property inheritance. If there is a __get() method in the parent object, and you implement your own __get() method in the subclass, your object will not execute correctly because the __get() method of the parent class will never will be called, of course it can be solved with parent::__get() Disadvantages: Relatively slow speed Using the magic accessor method makes it impossible to use reflection classes. Tools such as phpdocumentor can automatically document the code Cannot use it with static properties http://www.bkjia.com/PHPjc/628862.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628862.htmlTechArticleObject-oriented programming is a commonly used method in PHP. This article will introduce the simple method of using PHP object-oriented and Friends in need of some basic knowledge can enter for reference. (OOP) to develop...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn