Home  >  Article  >  Backend Development  >  PHP classes and objects full analysis (1)_PHP tutorial

PHP classes and objects full analysis (1)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:10:39851browse

Full analysis of PHP classes and objects (1)

1. Classes and Objects
Object: An individual that actually exists in each physical object of this type. $a =new User(); $a
after instantiation
Quote: PHP alias, two different variable names point to the same content
Encapsulation: Organize the properties and methods of an object into a class (logical unit)
Inheritance: Create a new class based on the original class for the purpose of code reuse;
Polymorphism: allows assigning a pointer of a subclass type to a pointer of a parent class type.
----------------------------------------
2. Automatically load objects:
Automatic loading defines a special __autoload function, which is automatically called when a class that is not defined in the script is referenced.
1 [php] view plaincopyprint?
2 function __autoload($class){
3 require_once("classes/$class.class.php");
4 }
Why use __autoload
1. First of all, I don’t know where this class file is stored.
2. The other one is that I don’t know when I need to use this file.
3. Especially when there are a lot of project files, it is impossible to write a long string of require at the beginning of each file...
replaces one
require_once ("classes/Books.class.php") ;
require_once ("classes/Employees.class.php" ) ;
require_once ("classes/Events.class.php") ;
require_once ("classes/Patrons.class.php") ;
zend recommends one of the most popular methods, including the path in the file name. For example, the following example:
1 [php] view plaincopyprint?
2
3 view sourceprint?
4 // Main.class
5
6 function __autoload($class_name) {
7 $path = str_replace('_', DIRECTORY_SEPARATOR, $class_name);
8 require_once $path.'.php';
9 }  
temp = new Main_Super_Class();
All underscores will be replaced with separators in the path. In the above example, the Main/Super/Class.php file will be reached.
Disadvantages:
In the coding process, you must clearly know where the code file should be,
And since the file path is hard-coded in the class name, if we need to modify the folder structure, we must manually modify all class names.
If you are in a development environment and don't care much about speed, it is very convenient to use the 'Include All' method.
By placing all class files in one or several specific folders, and then finding and loading them through traversal.
For example
$arr = array (
'Project/Classes',
'Project/Classes/Children',
'Project/Interfaces'
);
foreach($arr as $dir) {
$dir_list = opendir($dir);
while ($file = readdir($dir_list)) {
$path = $dir.DIRECTORY_SEPARATOR.$file;
                                                                                                                                             
continue;
if (strpos($file, ".class.php"))
require_once $path;
                                                              
}
?>
Another method is to establish an associated configuration file between the class file and its location, for example:
view sourceprint?
// configuration.php
array_of_associations = array(
'MainSuperClass' = 'C:/Main/Super/Class.php',
'MainPoorClass' = 'C:/blablabla/gy.php'
);
Called file
require 'autoload_generated.php';
function __autoload($className) {
global $autoload_list;
require_once $autoload_list[$className];
} }
$x = new A();
?>
-------------------------------------------------- -
3. Constructor and destructor
PHP constructor __construct() allows the constructor to be executed before instantiating a class.
Constructor is a special method in a class. When using the new operator to create an instance of a class, the constructor will be automatically called, and its name must be __construct().
(Only one constructor can be declared in a class, but the constructor will only be called once every time an object is created. This method cannot be called actively,
So it is usually used to perform some useful initialization tasks. This method has no return value. )
Function: Used to initialize objects when creating objects
The subclass executes the classified constructor parent::__construct().
Destructor: __destruct () definition: special internal member function, no return type, no parameters, cannot be called at will, and no overloading;
It’s just that when the life of the class object ends, the system automatically calls to release the resources allocated in the constructor.
Corresponding to the constructor method is the destructor method. The destructor method allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc.
The destructor cannot take any parameters and its name must be __destruct().
Function: Clean up the aftermath work, for example, use new to open up a memory space when creating an object, and use the destructor to release the resources allocated in the constructor before exiting.
Example:
class Person {
public $name;
public $age;
//Define a constructor initialization assignment
public function __construct($name,$age) {
$this->name=$name;
$this->age=$age;
} }
public function say() {
echo "my name is :".$this->name."
";
echo "my age is :".$this->age;
} }
//Destructor
function __destruct()
{
echo "goodbye:".$this->name;
} }
}
$p1=new Person("ren", 25);
$p1->say();
-------------------------------------------------- ----------------
4. Access control
Access control of properties or methods is achieved by adding the keywords public, protected or private in front
Class members defined by public can be accessed from anywhere;
Class members defined by protected can be accessed by subclasses and parent classes of the class in which they are located (of course, the class in which the member is located can also be accessed);
Class members defined as private can only be accessed by the class in which they are located.
Access control on class members
Class members must be defined using the keywords public, protected or private
Access control on methods
Methods in a class must be defined using the keywords public, protected or private. If these keywords are not set, the method will be set to the default public.
Example:
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // This line can be executed normally
echo $obj->protected; // This line will generate a fatal error
echo $obj->private; // This line will also generate a fatal error
$obj->printHello(); // Output Public, Protected and Private
-------------------------------------------------- ---------------
5. Object inheritance
Inheritance definition: Create a new class based on the original class for the purpose of code reuse;
-------------------------------------
Overwriting is used in object inheritance
Overloading is a method with the same method name but different parameters in a single object
-------------------------------------
Inheritance is a well-known programming feature, and PHP’s object model also uses inheritance. Inheritance will affect the relationship between classes and objects, and between objects.
For example, when extending a class, the subclass will inherit all the public and protected methods of the parent class. But the methods of the subclass will override the methods of the parent class.
Inheritance is very useful for functional design and abstraction, and adding new functions to similar objects eliminates the need to rewrite these common functions.
class Person {
public $name;
public $age;
function say() {
echo "my name is:".$this->name."
";
echo "my age is:".$this->age;
} }
}
// Class inheritance
class Student extends Person {
var $school; //Attributes of the school where the student is located
function study() {
echo "my name is:".$this->name."
";
echo "my school is:".$this->school;
                                                                        
}
$t1 = new Student();
$t1->name = "zhangsan";
$t1->school = "beijindaxue";
$t1->study();
------ --------- ------ --------- -------- -----
6. Range parsing operator (::)
The scope resolution operator (also known as Paamayim Nekudotayim) or more simply a pair of colons can be used to access static members, methods and constants, and can also be used to override members and methods in a class.
When accessing these static members, methods and constants outside the class, the class name must be used.
The two special keywords self and parent are used to access members or methods inside the class.
Note:
When a subclass overrides a method in its parent class, PHP will no longer execute the overridden methods in the parent class until these methods are called in the subclass
Example:
class OtherClass extends MyClass
{
public static $my_static = 'static var';
public static function doubleColon() {
echo parent::CONST_VALUE . "n";
echo self::$my_static . "n";
} }
}
OtherClass::doubleColon();
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/934463.htmlTechArticleFull Analysis of PHP Classes and Objects (1) 1. Classes and Objects: The actual existence of each thing of this type physical entity. $a =new User(); Reference to $a after instantiation: php alias, two different...
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