- Call class and pass constructor parameters in PHP
- Call class and pass constructor parameters in PHP
- Php classes : Passing parameters to constructor
- Class argument and parameter passing in php
- Typed Properties — Constructors & Destructors
- PHP passing arguments into class’s constructor dynamically
- Counting parameters of object constructor (external method)
- Pass arguments from array in PHP to constructor
- Example
- Output
- Php constructor with parameters in php code example
- Constructor in PHP
- Use the PHP Constructor to Initialize the Properties of an Object in a Class
- Use the PHP Constructor to Initialize the Properties of an Object with Parameters in a Class
- Initiate an Object in a Child Class and Call the Parent Class Constructor When Both Classes Have Individual Constructors in PHP
- PHP Pass an Object as a Parameter via the Constructor
- Counting parameters of object constructor (external method)
Call class and pass constructor parameters in PHP
The Reflection API can be used to pass arguments from array to constructor. ReflectionClass::newInstanceArgs The above line creates a new class instance from given arguments − It creates a new instance of the class when the arguments are passed to the constructor. I can count the number of passed arguments to constructor, but I will need to check that inside object constructor and that method does not help me.
Call class and pass constructor parameters in PHP
call_user_func_array(array($className, $methodName), array($_POST)) ;
To call a function in my class and send it parameters.
But how would I go about calling just the class and passing it parameters that go into the __constructor?
$myTable = new Supertable(array('columnA', 'columnB'), 5, 'Some string') ;
Which would work. What function do I need to achieve something similar to what call_user_func_array does?
Here it is in the full context of what I’m doing:
function __autoload($classname) < @include $classname.'.php' ; >$className = 'supertable' ; $methodName = 'main' ; if(class_exists($className, true)) < if(method_exists($className, $methodName)) < $reflection = new ReflectionMethod($className, $methodName) ; if($reflection->isPublic()) < call_user_func_array(array($className, $methodName), array($_POST)) ; >elseif($reflection->isPrivate()) < echo 'elseif($reflection->isProtected()) < echo '> else < echo 'The method > else
Found the answer to my own question here:
How to call the constructor with call_user_func_array in PHP
For reference, I altered my script like so:
function __autoload($classname) < @include $classname.'.php' ; >$className = 'supertable' ; $methodName = '' ; if(class_exists($className, true)) < if(method_exists($className, $methodName)) < $reflection = new ReflectionMethod($className, $methodName) ; if($reflection->isPublic()) < call_user_func_array(array($className, $methodName), array($_POST)) ; >elseif($reflection->isPrivate()) < echo 'elseif($reflection->isProtected()) < echo '> else < $reflect = new ReflectionClass($className); $reflect->newInstanceArgs(array($_POST)); > > else
So if the class exists but no method is given it calls the constructor.
If that is exactly what you need, I don’t see the whole point, for 2 reasons:
- You can call it easily this way:
PHP constructor with a parameter, Constructors can take parameters like any other function or method in PHP: class MyClass < public $param; public function
Php classes : Passing parameters to constructor
Constructor is the first function that gets called when a new class is created. Destructor on the Duration: 8:49
Class argument and parameter passing in php
parameter constructor in php: how to create parameter and pass arguments inside class
Duration: 5:16
Typed Properties — Constructors & Destructors
In this lesson, you will learn all about classes & objects in PHP. How to create classes
Duration: 21:15
PHP passing arguments into class’s constructor dynamically
I’ve written a PHP class in my project’s framework that contains a constructor, and for the purposes of this class it contains a single argument called name .
My class is loaded dynamically as part of the feature I’m building and I need to load a value into my argument from an array, but when I do this it just comes through as Array even when I use array_values , e.g, here’s my class:
name = $name; > /** * Write data to a file */ public function writeToFile($data = '') < $file = fopen('000.txt', 'w'); fwrite($file, $data); fclose($file); >/** * Execute the job. * * @return void */ public function handle() < try < $this->writeToFile('Hello ' . $this->name); > catch (Exception $e) < // do something >> >
/** * Get the job */ public function getJob($job = '') < return APP . "modules/QueueManagerModule/Jobs/$job.php"; >/** * Check that the job exists */ public function jobExists($job = '') < if (!file_exists($this->getJob($job))) < return false; >return true; > /** * Execute the loaded job */ public function executeJob($class, $rawJob = [], $args = []) < require_once $this->getJob($class); $waitTimeStart = strtotime($rawJob['QueueManagerJob']['available_at']) / 1000; $runtimeStart = microtime(true); // initiate the job class and invoke the handle // method which runs the job $job = new $class(array_values(unserialize($args))); $job->handle(); >
$args would look like this:
How can I dynamically pass args through to my class in the order that they appear and use the values from each.
array_values () still returns an array. All it does it resetting keys to be consecutive zero-based integers.
I think you want to use the splat operator:
$job = new $class(. array_values(unserialize($args)));
> $class = 'GreetingJob'; $args = serialize( [ 'name' => 'Jimmy', ] ); $job = new $class(. array_values(unserialize($args)));
Beware that the overall design can be confusing. Accepting arguments in an associative array suggests names matter and position doesn’t, but it’s the other way round.
this is the way to instantiate a class dynamically using Reflection in php:
$className = 'GreetingJob'; $args = []; $ref = new \ReflectionClass($className); $obj = $ref->newInstanceArgs($args);
PHP passing arguments into class’s constructor dynamically, I’ve written a PHP class in my project’s framework that contains a constructor, and for the purposes of this class it contains a single argument
Counting parameters of object constructor (external method)
I write a code that autoload classes , and I encountered a problem which I think is because of weakness implementation/design type. What I want to do is to count default parameters of an object (external). I can count the number of passed arguments to constructor, but I will need to check that inside object constructor and that method does not help me.
CODE EXAMPLE:
// This is simple function test($arg1,$arg2,$arg3) // How can I count like this? class load < public function __construct($id="",$path="") <>> $l = new load(); // How to count object default parameters count(object($l)), I need answer to be 2`
MY CODE WHERE I NEED TO USE THIS METHOD:
[File: global_cfg.php]
false, "NaNExist" => true, "Message" => array(MODE), "Debug" => DEBUG, "Resource" => true, "View" => true );
[File: autoload_classes.php]
Loaded classes:
"; function __autoloadClasses($list, $suffix="class", $extension="php") < $path=""; foreach($list as $fileName =>$classInstance) < $path = ROOT.DS.LIB.DS.$fileName.".".$suffix.".".$extension; if(!file_exists($path)) < print "Signed class ".$fileName." does not exist!
"; continue; > require_once($path); print $path; if($classInstance) < $GLOBALS[strtolower($fileName)] = new $fileName(); // . todo: counting default object parameters $count = count(get_object_vars($GLOBALS[strtolower($fileName)])); if(is_array($classInstance)) < if($countelse if($count>count($classInstance)) < print "Insuficient arguments passed to the object!"; >else < // todo: create object and pass parameters $GLOBALS[strtolower($fileName)] = new $fileName(/*$arg1 .. $argn*/); >> print $count." -> Class was instantiated!
"; continue; > print "
"; > >__autoloadClasses($signClasses);
After this problem I can finish my bootstrap.
You can use ReflectionFunctionAbstract::getNumberOfParameters. For example.
class load < public function __construct($id = "", $path = "") < >> function getNumberOfParameters($class_name) < $class_reflection = new ReflectionClass($class_name); $constructor = $class_reflection->getConstructor(); if ($constructor === null) return 0; else return $constructor->getNumberOfParameters(); > var_dump(getNumberOfParameters('load'));
How to make PHP version 8 support constructor with same name as, I have a legacy project being migrated to PHP version 8, but the new PHP version doesn’t support class constructor named based on the class
Pass arguments from array in PHP to constructor
The Reflection API can be used to pass arguments from array to constructor.
ReflectionClass::newInstanceArgs
The above line creates a new class instance from given arguments −
public ReflectionClass::newInstanceArgs ([ array $args ] ) : object
It creates a new instance of the class when the arguments are passed to the constructor. Here, args refers to the arguments that need to be passed to the class constructor.
Example
newInstanceArgs(array('substr')); var_dump($my_instance); ?>
Output
This will produce the following output −
object(ReflectionFunction)#2 (1) < ["name"]=>string(6) "substr" >
How to implement php constructor that can accept different number, Constructor arguments work just like any other function’s arguments. Simply specify defaults php.net/manual/en/… or use func_get_args().
Php constructor with parameters in php code example
Output: Initiate an Object in a Child Class and Call the Parent Class Constructor When Both Classes Have Constructors in PHP Output: The class extends the class in the code above. Last, we will see how you can initiate an object in a and call the constructor when both classes have individual constructors.
Constructor in PHP
In this tutorial, we will introduce the PHP constructor. We will see how you can use the __construct() function to initialize the properties of an instance in a class.
We will also use the function to initialize the properties of objects with given parameters in a class.
Last, we will see how you can initiate an object in a child class and call the parent class constructor when both classes have individual constructors.
Use the PHP Constructor to Initialize the Properties of an Object in a Class
In the example below, we will create a class Student and use the __construct function to assign new Student its properties.
The __construct function reduces the number of codes associated with using the function set_name() .
name = $name; $this->email = $email; > function get_name() < return $this->name; > function get_email() < return $this->email; > > $obj = new Student("John", "john567@gmail.com"); echo $obj->get_name(); echo "
"; echo $obj->get_email(); ?>
Use the PHP Constructor to Initialize the Properties of an Object with Parameters in a Class
In the example code below, we create the class Military and use the __construct function to give the properties and parameters of the objects we create.
name = $name; $this->rank = $rank; > function show_detail() < echo $this->name." : "; echo "Your Rank is ".$this->rank."\n"; > > $person_obj = new Military("Michael", "General"); $person_obj->show_detail(); echo "
"; $person2 = new Military("Fred", "Commander"); $person2->show_detail(); ?>
Michael : Your Rank is General Fred : Your Rank is Commander
Initiate an Object in a Child Class and Call the Parent Class Constructor When Both Classes Have Individual Constructors in PHP
name = $name; > >class Identity extends Student < public $identity_id; public function __construct($name, $identity_id) < parent::__construct($name); $this->identity_id = $identity_id; > function show_detail() < echo $this->name." : "; echo "Your Id Number is ".$this->identity_id."\n"; > > $obj = new Identity('Alice', '1036398'); echo $obj->show_detail(); ?>
Alice : Your Id Number is 1036398
The class Identity extends the class Student in the code above. We use the keyword parent: to call the constructor for the Student class.
PHP OOP Constructor, A constructor allows you to initialize an object’s properties upon creation of the object. If you create a __construct () function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)! We see in the example below, that using a constructor saves us
PHP Pass an Object as a Parameter via the Constructor
First, I would change the method readCreds in the class GetCredentials and make sure it assigns the credentials in the private variables of the class:
public function readCreds($filename) < $parray = []; $file = fopen($filename,"r"); while(! feof($file)) < array_push($parray, fgets($file)); >fclose($file); $this->DB($parray[0]); $this->Uname($parray[1]); $this->Pwd($parray[2]); >
After I would test it as such:
$sC = New GetCredentials(); $sC->readCreds('dbdata.txt'); echo $sC->DB(); echo $sC->Uname(); echo $sC->Pwd();
Then in the DBconnection class, I would change the constructor to properly assign those credentials to the private variables. And I would add $this keyword when using those variables to instantiate the PDO object :
// DBconnection class DBconnection< private $conn; private $Uname; private $DB; private $Pwd; public function __construct(GetCredentials $cr) < $this->Uname = $cr->Uname(); $this->DB = $cr->DB(); $this->Pwd = $cr->Pwd(); > public function dbConnect($sql) < try < $this->conn = new PDO("mysql:host=localhost;dbname=" . $this->DB, $this->Uname, $this->Pwd); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $arr = $this->conn->prepare($sql); $arr->execute(); $result = array(); $result = $arr->fetchAll(); return $result; > catch(PDOException $err) < return "ERROR: Unable to connect: " . $err->getMessage(); > > function __destruct() < $conn = null; >>
Test if this solves your problem.
Constructor in PHP, Use the PHP Constructor to Initialize the Properties of an Object with Parameters in a Class In the example code below, we create the class Military and use the __construct function to give the properties and parameters of …
Counting parameters of object constructor (external method)
You can use ReflectionFunctionAbstract::getNumberOfParameters. For example.
class load < public function __construct($id = "", $path = "") < >> function getNumberOfParameters($class_name) < $class_reflection = new ReflectionClass($class_name); $constructor = $class_reflection->getConstructor(); if ($constructor === null) return 0; else return $constructor->getNumberOfParameters(); > var_dump(getNumberOfParameters('load'));
PHP | Constructors and Destructors, Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables. Once the object is initialized, the constructor is automatically called. Destructors are …