note 70876 deleted from language.oop5.decon by cmb

From: Date: Sun, 08 Sep 2019 10:26:22 +0000
Subject: note 70876 deleted from language.oop5.decon by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212139@lists.php.net to get a copy of this message
Note Submitter: phaxius ---- Hello, I've been messing with php for about a week but am learning a lot. It occurred to me that it might be necessary in some cases to write a class that takes a variable number of arguments. After some experimentation, this example was formed: class variableArgs{ public $a = array(); protected $numOfArgs; public function __construct() { $numOfArgs=func_num_args(); if(func_num_args()==0) { $numOfArgs=1; $a[0]='No arguments passed'; $this->Arg[0]=$a[0]; } else for($i=0; $i<func_num_args(); $i++) { $a[$i]=func_get_arg($i); $this->Arg[$i]=$a[$i]; } } public function showArgs() { echo 'showArgs() called <br />'; for ($i=0; $i<$numOfArgs; $i++) { echo '$i: ' . $i . '<br />'; echo $this->Arg[$i]; echo '<br />'; } } public function __destruct(){} } $test1 = new variableArgs; $test2 = new variableArgs("arg1"); $test3 = new variableArgs("arg1", "arg2"); $test4 = new variableArgs("arg1", "arg2", "arg3"); $test1->showArgs(); $test2->showArgs(); $test3->showArgs(); $test4->showArgs(); This outputs the following: showArgs() called $i: 0 No arguments passed showArgs() called $i: 0 arg1 showArgs() called $i: 0 arg1 $i: 1 arg2 showArgs() called $i: 0 arg1 $i: 1 arg2 $i: 2 arg3 I have no idea how efficient this is, but it works at any rate. Hopefully this helps someone.

« previous php.notes (#212139) next »