简体   繁体   中英

php create a new object instance using a boolean

I'm having a difficult time googling an explanation of a line of php code in a script I'm modifying. It is doing the following, where $boolean is a variable set to true or false.

$var = new class($boolean);

What is the significance of the boolean? Thanks.

This line is creating an instance of class using it's constructor function which is just a function in a class that returns an object. $boolean is the argument to the constructor function new is a php keyword used for creating instances of classes and $var is the variable to store the returned object in.

The variables passed into the class, will be used to initialize the workings. Without seeing the constructor, it's hard to say the significance of the initializing variables.

In object oriented languages, when you define a class you create constructors. The constructors are functions of the type ClassName() or ClassName(Parameters), and you use the new operator with these to create an instance of the class.

The default constructor is an empty one, ie no parameters. But you can also create constructors that take parameters. Those are typically used to initialize the member variables of the class. So in your example, the boolean is a parameter to one of the constructors. What exactly it means can only be determined either from the documentation or the code.

Here is an example (not PHP):

class SomeClass
{
     private int x;
      public SomeClass() { this.x = 5; }
     public SomeClass(int xx) { this.x = xx; }
}

The empty constructor sets the member x to 5. The constructor with the parameter sets the member x to whatever was passed in. To understand what your boolean is doing, you would have to look at the class definition and see what the constructor that takes in the boolean is doing with it.

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