PHP constructor Problems

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.