简体   繁体   中英

PHP use case scenarion when should I use function __construct

I am starting to learn PHP OOP following a prescribed book, however it is not the best of books IMO and results in quite a bit of confusion especially the section on PHP classes.

Consider the folllowing:

     Class User{

    function setName($newName)
        {
            $this->name = $newName;
        }

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

The class has no construct method:

Thus, my Questions:

  1. If the class above had a property $name and a function __construct refrencing the $name var would it have been necessary to create the setName() method?

  2. If yes, When is it appropriate to build a construct method? And when is it not? As a general rule of thumb am I correct to assume it is good practice to build a construct method for all class properties?

Any advice / help / references appreciated.

There are 2 scenarios where setName and __construct can be used.

1 - When you create an object of class and you want to class should be initailized with default parameter then go with __construct method.

$obj = new UserName('john'); 

Above method cannot be used multiple times right. so that you need a way where you can change a name without creating an object every time that where setName comes in picture.

2 - setName is way to reinitialize the name property whenever it's required.

  $obj = new UserName('john'); //1st step
  echo $obj->getName(); //john displays
  //may be some sql query that gets name from db
  $obj->setName('david'); //here you cannot re-instantiate the object to set the name using construct method.
  $obj->getName(); //david displays

Hope this heps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM