Php class parameters passed

Passing static methods as arguments in PHP

so that ‘myFunction’ will have a reference to the static method and be able to call it. When I try it, I get an error of «Undefined class constant» (PHP 5.3) so I guess it isn’t directly possible, but is there a way to do something similar? The closest I’ve managed so far is pass the «function» as a string and use call_user_func().

8 Answers 8

The ‘php way’ to do this, is to use the exact same syntax used by is_callable and call_user_func.

This means that your method is ‘neutral’ to being

  • A standard function name
  • A static class method
  • An instance method
  • A closure

In the case of static methods, this means you should pass it as:

myFunction( [ 'MyClass', 'staticMethod'] ); 

or if you are not running PHP 5.4 yet:

myFunction( array( 'MyClass', 'staticMethod') ); 

Helped a lot since call_user_func(function($foo) < echo $foo;>, ‘foo’) is as valid as call_user_func([ ‘MyClass’, ‘staticMethod’], ‘foo’);

Since you’ve already mentioned that call_user_func() has been used and you’re not interested in a solution with that or ones that are passing the static function as a string, here is an alternative: using anonymous functions as a wrapper to the static function.

function myFunction( $method ) < $method(); >myFunction( function() < return MyClass::staticMethod(); >); 

I wouldn’t recommend doing this, as I think the call_user_func() method is more concise.

If you want to avoid strings, you can use this syntax:

It is a little verbose, but it has the advantage that it can be statically analysed. In other words, an IDE can easily point out an error in the name of the static function.

Let my try to give a thorough example.

You would make a call like this:

myFunction('Namespace\\MyClass', 'staticMethod'); 

or like this (if you have arguments you want to pass):

myFunction('Namespace\\MyClass', 'staticMethod', array($arg1, $arg2, $arg3)); 

And your function to receive this call:

public static function myFunction($class, $method, $args = array()) < if (is_callable($class, $method)) < return call_user_func_array(array($class, $method), $args); >else < throw new Exception('Undefined method - ' . $class . '::' . $method); >> 

Similiar technique is commonly used in the Decorator Pattern in php.

In PHP is it possible to do something like this:

myFunction( MyClass::staticMethod );

the answer is yes. you can have the staticMethod() return anonymous function instead. i.e.

private static function staticMethod() < return function($anyParameters) < //do something here what staticMethod() was supposed to do // . // . //return something what staticMethod() was supposed to return; >; > 
myFunction(MyClass::staticMethod()); 

but note that () is needed to invoke staticMethod(). This is because it now returns the anonymous function that wraps the job of what you initially wanted your staticMethod() to do.

This works perfectly fine when staticMethod() is only being passed in as parameter into another function. If you wish to call staticMethod() that directly does the processing, you have to then write

MyClass::staticMethod()($doPassInParameters); 

Note that this may require one extra redundant step to retrieve the function pointer, as compared to when it can work without wrapping it in anonymous function. I only use it to pass as parameter so am not sure of the performance penalty of the extra step. Perhaps negligible .

Читайте также:  Structure of java application

Источник

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:

Читайте также:  Zip на сервере php

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

Читайте также:  Java database management system

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 5 passing class Object as parameter, is it always a pointer or a copy or a clone?

I have a question about passing object as parameter. When we pass a variable, it creates a copy, but looks like object is always a reference pointer, is this correct? I have tested with the following example code:

class Base < private $var; function set ($var) < $this->var = $var; > function show () < echo $this->var, '
'; > > class Car < private $obj; function __construct($obj) < $this->obj = $obj; > function set ($var) < $this->obj->set($var); > function show() < $this->obj->show(); > > class Bus < private $obj; function __construct($obj) < $this->obj = $obj; > function set ($var) < $this->obj->set($var); > function show() < $this->obj->show(); > >
$base = new Base(); $base->set('one'); $base->show(); // one $bus = new Bus($base); $bus->show(); // one $car = new Car($base); $car->set('two'); $car->show(); // two $base->show(); // two $bus->show(); // two 

So changing the Base class’s variable anywhere even it was passed as parameter into a function or another class will affect all of them, so does this mean it’s always pointing to a same object as a pointer? Thank you.

Objects are passed by references by default. But actully, php reference isn’t real reference and every time you pass an object the php proccesor create new object that are identical and if you change one it will change the another.

1 Answer 1

In PHP When you pass object as parameter, it is copy of the reference. So:

$ob = new StdClass; $ob->var = "Lorem"; function aa($o) < $o->var="Ipsum"; > aa($ob); echo $ob->var; 

this will output Ipsum , but if you assign other object to that $o reference:

It will output Lorem — because $ob still points to previously created object.

By the way: If you change function definition to function aa(&$o) . Now it will output Ipsum again, because $o is reference to $ob reference 🙂

To sum up: In PHP by default parameters are passed by value — also if they are objects! But! In code $ob = new StdClass; , $ob is reference to the object. So by default we will pass copy of the reference. They will point to the same objects. But if you change passed variable ( $o = new StdClass; ), $ob still points to the same object. That’s why after that modification given example will output Lorem .

You can pass parameters by reference using ampersand (&), but in case of objects it is usually useless.

Источник

Оцените статью