Home > PHP Framework > ThinkPHP > body text

How to set the constructor in ThinkPHP

WBOY
Release: 2023-05-27 11:30:59
forward
1164 people have browsed it

1. What is a constructor function

The constructor is a special function that is automatically called when instantiating an object. Its function is to initialize the object, set the initial value of the properties, etc. In PHP, the name of the constructor must be __construct().

2. Steps to set the constructor in ThinkPHP

  1. First we need to create a class file, for example we can create a PHP file , named test.php, the code is as follows:

<?php
namespace Home\Model;
use Think\Model;
class test extends Model{
    private $name;
    public function __construct($name){
        $this->name = $name;
    }
    public function get_name(){
        return $this->name;
    }
}
Copy after login
  1. In the test class, a private attribute $name is defined, and there is also a public method get_name( ). We use the $name parameter to assign an initial value to the $name attribute in the constructor __construct().

  2. When using the test class, we can instantiate the object as follows:

$t = new test("thinkphp");
echo $t->get_name();
Copy after login
  1. Instancing At the same time as the object, we passed a string "thinkphp" as a parameter. This parameter will be passed to the constructor __construct() of the class and used to set the initial value of the attribute $name. Finally, we use the get_name() function to extract the value of the $name attribute and output it.

3. Advantages of using constructors

The advantage of using constructors is that you can complete some necessary tasks when the class is instantiated. Initialization operation avoids writing some additional initialization code when using classes. In this way, it is more convenient to use.

The above is the detailed content of How to set the constructor in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!