Method 1: What are the essential differences between {code...} and {code ?? Statement 1:
class test{ public $db= new PDO;}
Statement 2
class test { public $db; public function __construct() { $this->db=new PDO; }}
What are the essential differences between the two statements ??
Reply content:
Statement 1:
class test{ public $db= new PDO;}
Statement 2
class test { public $db; public function __construct() { $this->db=new PDO; }}
What are the essential differences between the two statements ??
The first method is incorrect:
Http://php.net/manual/zh/language.oop5.properties.php
Attribute
The variable members of a class are called "attributes", "fields", and "Features". In this document, they are collectively referred to as "attributes ". Attribute Declaration starts with the keyword public, protected, or private, and then starts with a common variable declaration. The variables in the attribute can be initialized, but the initialization value must beConstantThe constant here means that the PHP script can obtain its value at the compilation stage, and can be evaluated without the information at the runtime.
1. The first write method reports an error. The initial value of the class attribute can only be a scalar.
2. Modify the second Writing Method:
class test { public $db; public function __construct(PDO $pdo) { $this->db = $pdo; }}$test = new Test(new PDO);
The member variables you define in the class cannot be assigned values through class instantiation and function return values. The first write method will report an error, and you certainly did not execute code on the machine, you can execute the two statements on the machine.
Constructor is the first function called after the class is instantiated. It will make some preparations in it, for example, instantiate other classes and assign values to member variables based on input parameters.