PHP constructor with a parameter

前端 未结 2 893
北海茫月
北海茫月 2020-12-24 10:35

I need a function that will do something like this:

$arr = array(); // This is the array where I\'m storing data

$f = new MyRecord(); // I have __constructo         


        
相关标签:
2条回答
  • 2020-12-24 11:05

    Read all of Constructors and Destructors.

    Constructors can take parameters like any other function or method in PHP:

    class MyClass {
    
      public $param;
    
      public function __construct($param) {
        $this->param = $param;
      }
    }
    
    $myClass = new MyClass('foobar');
    echo $myClass->param; // foobar
    

    Your example of how you use constructors now won't even compile as you can't reassign $this.

    Also, you don't need the curly brackets every time you access or set a property. $object->property works just fine. You only need to use curly-brackets under special circumstances like if you need to evaluate a method $object->{$foo->bar()} = 'test';

    0 讨论(0)
  • 2020-12-24 11:12

    If you want to pass an array as a parameter and 'auto' populate your properties:

    class MyRecord {
        function __construct($parameters = array()) {
            foreach($parameters as $key => $value) {
                $this->$key = $value;
            }
        }
    }
    

    Notice that a constructor is used to create & initialize an object, therefore one may use $this to use / modify the object you're constructing.

    0 讨论(0)
提交回复
热议问题