John Davidson

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

0 comments
Message:


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');
?>


My Answer:
To pass an array as a parameter in a class constructor in PHP, you can simply define the parameter as an array type in the constructor signature. Here's an example of how you can achieve this:

php
class MyClass {
private $tableName;
private $id;
private $tableFields;

public function __construct($tableName, $id, array $tableFields) {
$this->tableName = $tableName;
$this->id = $id;
$this->tableFields = $tableFields;
}

public function getTableName() {
return $this->tableName;
}

public function getId() {
return $this->id;
}

public function getTableFields() {
return $this->tableFields;
}
}

// Usage
$tableName = 'users';
$id = 'user_id';
$tableFields = ['name', 'email', 'phone'];

$myClass = new MyClass($tableName, $id, $tableFields);

echo $myClass->getTableName(); // Output: users
echo $myClass->getId(); // Output: user_id
print_r($myClass->getTableFields()); // Output: Array ( [0] => name [1] => email [2] => phone )


In this example, the `tableFields` parameter is defined as an array type in the constructor signature. When creating an instance of the `MyClass` class, you can pass an array of field names as the third parameter. You can then access and use this array within the class as needed.

Rate this post

3 of 5 based on 2882 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us