简体   繁体   中英

How to pass an array as a parameter in a class constructor in PHP

I'm trying to pass these parameters in my class constructor:

  1. $tableName : Database table name.
  2. $id : ID field name of my database table.
  3. $tableFields : Field names of my database table.

Parameter 1 and 2 always will be only 1, but parameter 3 is variable, maybe 2, maybe 4 or maybe 15.

So, I need to save it into an array, but I'm not sure how to do it.

Guys, can you help me to understand this?

<?php
    class GenerateCrud {
    
        // Properties.
        
            public $tableName;
            public $id;
            public $tableFields = array();
    
        // Constructor.
        
            function __construct($tableName, $id, $tableFields){
                $this->tableName = $tableName;
                $this->id = $id;
                $this->tableFields[] = $tableFields;
            }
    }
    
    $myObject = new GenerateCrud('users_test', 'id', 'field1', 'field2', 'field3', 'field4');
?>

Add:

$this->tableFields = $tableFields;

And:

$myObject = new GenerateCrud('users_test', 'id', ['field1', 'field2', 'field3', 'field4']);

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