Is it possible to use public functions inside a public function in php?
I got a few public functions which change the input and return it. I want to make a for statement inside a public function that loops through my functions, like:
$input
for= function1 -> output1 -> function2->output2->function3->output3.
I want to use the output of that for my next function. Also the 4 functions I have in my for loop has to loop 9 times.
in this case its about AES encrypt. i got 4 functions called: subBytes, shiftRows, mixColumns, addRoundkey.
This is my public function encrypt:
public function encrypt($input)
{
$functions= ('subBytes', 'shiftRows', 'mixColumns', 'addRoundKey' );
foreach($functions as $function)
{
$input = $$function($input);
}
return($input);
} //end function encrypt
and this is one of my functions:
public function subBytes($state)
{
for ($row=0; $row<4; $row++){ // for all 16 bytes in the (4x4-byte) State
for ($column=0; $column<4; $column++){ // for all 16 bytes in the (4x4-byte) State
$_SESSION['debug'] .= "state[$row][$column]=" . $state[$row][$column] ."-->" . self::$sBox[$state[$row][$column]]."\n";
$state[$row][$column] = self::$sBox[$state[$row][$column]];
}
}
return $state;
}
Use code like this:
$output3 = function3(function2(function1($input)));
Or you can to add your function name into array and iterate over it:
$input = ''; // some value
$functioins = ('function1', 'function2', 'function3', 'function4');
foreach ($functions as $function) {
$input = $$function($input);
}
$output = $input;
If we try to use public functions of object then:
public function encrypt($input)
{
// array with methods names
$methods= array('subBytes', 'shiftRows', 'mixColumns', 'addRoundKey' );
foreach($methods as $method)
{
$input = $this->$method($input);
}
return($input);
}
Related
I am using php 7.4.9 and have a class which reads information from a file. These informations should be all the time availabe from outside the class and it also should possible to modify that array, so that this class can write back these information on request.
I have looked for a while but could not fined a useful solution.
I got the functions working, but the array loose the values from call to call.
Edit 2020/12/12
This is the uses structure of my code
<?php
.......
function show(){
$id3 = ID3::create();
$mp3 = &ID3::$mp3Array;
if($mode == "manual"){
if($file == ""){
return "";
}
$fName = $dir . "/" . $file;
$id3->open($fName);
.......
}else if($mode == "save"){
$fName = $dir . "/" . $file;
$id3->save($fName);
return "Save done!";
}
} // end of show
class ID3{
public static $mp3Array = array();
public static function create(): self {
static $object;
$object = $object ?? new self();
return $object;
}
function open($fName){
$mp3 = self::$mp3Array;
. // $mp3 will be filled
.........
}
function save($fName) {
$mp3 = &ID3::§mp3Array;
error_log("TagSave: ".var_export($mp3, true),0); // is always empty
foreach($mp3 as $key => $value){
........
}
}
} //end of class>
?>
If I try to save the modified array, it is always empty, if show is called again!
I have also implemented the #Logifire proposal 'create'. I got a valid pointer but the arrayis still empty.
Maybe I should point out, that it is web page. The html code sends information (form) back to the php program.
I figured out, that use of global $id3 = NULL; does not work, because the php grogramm will be always called and set the variable again to NULL each time.
I have also implemented the following code on the beginning
<?php
error_log("PHP call",0);
$id3count = 0;
if(array_key_exists("Test_id3",$GLOBALS)){
error_log("GLOBALS[Test_id3] exist!",0);
}else{
error_log("GLOBALS[Test_id3] does not exist!",0);
$GLOBALS['Test_id3'] = "NEW";
}
The $GLOBAL['Test_id3'] never exist, if the programm will be called!
I got the functions working, but the array loose the values from call to call.
As I understand you, your setup is not a long running app, you can not keep state between requests (calls).
But if you are aware of that, the issue may be you have a new instance of the class each time you call it within the same request flow, you may use a singleton if this is the case. I suggest using accessors in your class.
class MyDataList {
private array $my_array = [];
private function __construct()
{
}
public static function create(): self {
static $object;
$object = $object ?? new self();
return $object;
}
public function setArray(array $new_array): void {
$this->my_array = $new_array;
// open, write, close file..
}
public function getArray(): array {
return $this->my_array;
}
}
$my_data_list = MyDataList::create();
Based on your edited question (2020/12/12), I extended the example code:
class MyDataList {
private array $my_array = [];
private $file_path = '';
private function __construct()
{
}
public static function create(string $file_path): self {
static $object;
if ($object === null) {
$object = new self();
$stringified = file_get_contents($file_path) ?: '';
$array = json_decode($stringified, true) ?: [];
$object->file_path = $file_path;
$object->my_array = $array;
}
return $object;
}
public function setArray(array $new_array): void {
$this->my_array = $new_array;
$stringified = json_encode($new_array);
file_put_contents($this->file_path, $stringified);
}
public function getArray(): array {
return $this->my_array;
}
}
$my_data_list = MyDataList::create('/path/to/file');
Note: Be aware, you need to apply error handling
Comment answers:
Is the filepath connected to the array?
Well, you will write your data as JSON to a file each time you "modify" the array via the setArray()
Does it means, that the array is stored into a file and read out each time I try to connect again?
For each request you call create() it will instantiate the internal state of the array based on the stored data in the file. ATM. The file_get_contents call may have been wrapped and only called if the $object was not instantiated. (Now updated in the example)
So I have to call setArray($array); to save the data. I was looking for a soluting to keep the data without an management to save and read the array. Is this not possible with PHP?
Maybe you want to use a session variable to store your data? But it is individual per user and not long lived data - Link: https://www.php.net/manual/en/reserved.variables.session.php
In a standard PHP setup you can not have data/state between requests, but there are solution like Swoole which makes PHP a long running app: https://www.php.net/manual/en/book.swoole.php
I need a possibility to modify the array directly.
Is it a reference to the array you want? https://3v4l.org/OsBC6
class MyDataList {
private array $my_array = [];
private function __construct()
{
}
public static function create(): self {
static $object;
$object = $object ?? new self();
return $object;
}
public function setArray(array &$new_array): void {
$this->my_array = &$new_array;
}
public function getArray(): array {
return $this->my_array;
}
}
There is no easy way to do with PHP!
Finally I use the proposal from Logifire, but had to modified it to fullfill my requirements.
I needed more than 1 array.
One array can ibclude binary data values, which json can't handle. So I have to use base64 for the binary data values.
Here my code:
public array $mp3Array = array();
public array $findArray = array();
private $file_dir = "";
public static function create(string $fileDir): self {
static $object;
if ($object === null) {
$object = new self();
$stringified1 = file_get_contents($fileDir."/mp3Array.obj") ?: '';
$array1 = json_decode($stringified1, true) ?: [];
$stringified2 = file_get_contents($fileDir."/findArray.obj") ?: '';
$array2 = json_decode($stringified2, true) ?: [];
$object->file_dir = $fileDir;
$object->mp3Array = $object->arrayDecode($array1);
$object->findArray = $array2;
}
return $object;
}
private function arrayEncode($arr){
$tmp = [];
foreach($arr as $key => $val){
if(is_array($val)){
$tmp[$key] = $this->arrayEncode($val);
}else if ($key == "data"){
$tmp[$key] = base64_encode($val);
}else{
$tmp[$key] = $val;
}
}
return $tmp;
}
private function arrayDecode($arr){
$tmp = [];
foreach($arr as $key => $val){
if(is_array($val)){
$tmp[$key] = $this->arrayDecode($val);
}else if ($key == "data"){
$tmp[$key] = base64_decode($val);
}else{
$tmp[$key] = $val;
}
}
return $tmp;
}
public function setMp3(array $new_array): void {
$this->mp3Array = $new_array;
$stringified = json_encode($new_array);
file_put_contents($this->file_dir."/mp3Array.obj", $stringified);
}
public function saveMp3(): void {
$base64 = $this->arrayEncode($this->mp3Array);
$stringified = json_encode($base64);
file_put_contents($this->file_dir."/mp3Array.obj", $stringified);
}
public function setFind(array $new_array): void {
$this->findArray = $new_array;
$stringified = json_encode($new_array);
file_put_contents($this->file_dir."/findArray.obj", $stringified);
}
public function saveFind(): void {
$stringified = json_encode( $this->findArray);
file_put_contents($this->file_dir."/findArray.obj", $stringified);
}
Here is my php code, the test method not giving wanted output, and the other weird thing is var_dump('a') print 3 times;
my wanted output is array('qtggccc','qtff23sdf');
public function main()
{
$serverIds = array('ff23sdf','ggccc');
$res = $this->test($serverIds);
var_dump($res);
}
public function test($serverIds,$imgArray = array())
{
if(count($serverIds) > 0){
$media_id = array_pop($serverIds);
$imgUrl= $this->hh($media_id);
array_push($imgArray,$imgUrl);
var_dump($serverIds);
var_dump($imgArray);
$this->test($serverIds,$imgArray);
}
var_dump('a');
return $imgArray;
}
public function hh($m)
{
return 'qt'.$m;
}
Try this:
class MyClass{
private $imgArray = array();
public function main(){
$serverIds = array('ff23sdf','ggccc');
$res = $this->test($serverIds);
print_r($this->imgArray);
}
public function test($serverIds){
if(count($serverIds) > 0){
$media_id = end($serverIds);
$imgUrl= $this->hh($media_id);
array_push($this->imgArray,$imgUrl);
//remove last element
array_pop($serverIds);
$this->test($serverIds);
}
return;
}
public function hh($m){
return 'qt'.$m;
}
}
$obj = new MyClass();
echo '<pre>';
$obj->main();
Why use recursion? You are using a complicated solution for a simple problem.
public function main()
{
$serverIds = array('ff23sdf','ggccc');
$res = array();
//These three lines replace an entire recursive function, making the code easier and saving a chunk of memory once you start using real arrays
foreach ($serverIds as $media_id){
array_unshift($res, $this->hh($media_id));
}
var_dump($res);
}
public function hh($m)
{
return 'qt'.$m;
}
I have a question on how to pass an array to a function in PHP. I have a class called "MyClass" and inside it has functions called rankVal($arr1, $arr2) and processResponse($data, $db, $id, $lat, $lng).
processResponse() will call rankVal() and here is my problem is.
class MyClass{
private function cmpVal($a, $b){
/*do sorting stuff*/
}
function rankVal($arr1, $arr2){
$arrIdx=[];
foreach ($arr1 as $key => $value) {
$n=array_search($value, $arr2);
$newPos = ($key+$n)/2;
$arrNewIdx [$n]=round($newPos,0, PHP_ROUND_HALF_DOWN);
}
}
function processResponse($data, $db, $id, $lat, $lng){
//Do some stuffs here...
$someArr1 = [];
foreach($results as $key => $value){
$newVal = new stdClass();
$newVal->key1 = $value->key1;
$newVal->key2 = $value->key2;
$newVal->key3 = $value->key3;
$newVal->key4 = $value->key4;
$newVal->key5 = $value->key5;
$someArr1 []= $newVal;
}
$someArr2 = $someArr1;
usort($someArr2, array($this, "cmpVal"));
$rankedVal = $this->rankVal($someArr1, $someArr2);
}
}
When I called the processResponse() function I got this error:
array_search() expects parameter 2 to be array, object given
So, I var_dump($arr2) in rankVal(), and the output clearly says that $arr2 is an array. Here's the sample output of the var_dump($arr2):
array(30) {
[0]=>
object(stdClass)#385 (7) {
["key1"]=>
string(24) "something"
["key2"]=>
string(20) "something"
["key3"]=>
string(41) "something"
["key4"]=>
float(1.23455)
["key5"]=>
float(1.19128371983198)
}
What did I do wrong? I tried to pass the array by reference by adding "&" in rankVal(&$arr1, &$arr2), but the error is still there.
To add to the other answer here (which now seems to have gone), if you want your class to behave as an array where appropriate, you need to make it iterable.
All you need to do is implement Iterable. This means that you need to create the necessary methods, but this is all you need in order to have your class behave that way.
Its useful for classes which are designed to hold an array of data, but you want to encapsulate additional tools along with that data.
Heres an example:
class Row implements \Iterator {
protected $data;
protected $position = 0;
public function __construct( array $data = [ ]) {
$this->data = $data;
}
public function addData( $value ) {
$this->data[] = $value;
}
public function replaceData( $index, $value ) {
$this->data[ $index ] = $value;
}
public function getData() {
return $this->data;
}
public function setData( array $data ) {
$this->data = $data;
return $this;
}
/** Required by Iterator */
public function current() {
return $this->data[ $this->position ];
}
/** Required by Iterator */
public function next() {
++$this->position;
}
public function __toArray() {
return $this->data;
}
/** Required by Iterator */
public function key() {
return $this->position;
}
/** Required by Iterator */
public function valid( $index = null ) {
return isset( $this->data[ $index ? $index : $this->position ] );
}
/** Required by Iterator */
public function rewind() {
$this->position = 0;
}
public function count() {
return count( $this->data );
}
}
Once you have this, it can be used anywhere you can use an array.
So after checking my code again, I finally found the problem that causing this weird bug which was not supposed to be there.
The culprit is in the rankVal() function where I called usort() which used rankVal() as the callback function for the sorting process. Then, I changed this callback function to the right one, and voila problem's solved.
Thanks for everyone who had answered and given me some suggestions on how to fix it.
I am building a PHP function to enqueue JavaScript files into a PHP array and then have another PHP function that will load all the JS files into a page and load them in the order based on a sort number that can be passed into the enqueue function. Similar to how WordPress loads JS and CSS files.
So my PHP function enqueue_js_script() might look like this below which takes in a key name for the JS file, a file path to the JS file, and a sort order number which is optional. It then would add the JS file to a PHP class property $this->_js_files[$script_key]...
public function enqueue_js_script($script_key, $file_source, $load_order = 0){
$this->_js_scripts[$script_key] = $file_source;
}
Then I will also have a PHP function load_js_scripts() which will print each script file path into the header of a webpages HTML.
This is where I want to take into consideration the $load_order passed into enqueue_js_script() to print the scripts into the HTML in the order based on these numbers.
How can I use this sort order number to sort my array of JS scripts?
UPDATE
It looks like I should store the sort number in an array like this instead...
$this->_js_files[$script_key] = array(
'file_source' => $file_source,
'sort' => $load_order
);
Using usort and a custom sorting function:
<?php
public function enqueue_js_script($script_key, $file_source, $load_order = 0){
$jsScript = new \stdClass;
$jsScript->load_order = $load_order;
$jsScript->script_key = $script_key;
$this->_js_scripts[$script_key] = $jsScript;
}
function sortJSFiles($a, $b)
{
if ($a->load_order == $b->load_order) {
return 0;
}
return ($a->load_order < $b->load_order) ? -1 : 1;
}
usort($this->_js_scripts, "sortJSFiles");
Having to pass your array key is not really good practice. The $array[] = $foo construction adds $foo as the new last item of $array.
Using usort.
<?php
class OrderStack {
private $contents = array();
public function add($order, $load) {
if (!is_int($order) || $order < 0) {
throw new InvalidArgumentException("$order must be a non-negative integer");
}
$this->contents[] = array($order, $load);
}
public function get_array() {
usort(
$this->contents,
'OrderStack::compare'
);
return array_map(
'OrderStack::get_load',
$this->contents
);
}
private static function get_load($stack_item) {
return $stack_item[1];
}
private static function compare($a, $b) {
return $a[0] - $b[0];
}
}
class YourClass {
private $_js_scripts;
public function __construct() {
$this->_js_scripts = new OrderStack();
}
public function enqueue_js_script($file_source, $load_order = 0) {
$this->_js_scripts->add($load_order, $file_source);
}
public function get_js_scripts() {
return $this->_js_scripts->get_array();
}
}
?>
The OrderStack class is reusable.
This question already exists:
Closed 11 years ago.
Possible Duplicate:
Any way to access array directly after method call?
In C# and other languages, I can do something like this
$value = $obj->getArray()[0];
But not in PHP. Any workarounds or am I doomed to do this all the time?
$array = $obj->getArray();
$value = $array[0];
No, you can't do it without using array_shift (Which only gets the first element). If you want to access the third or fourth, most likely you'd want to do a function like this:
function elemnt($array, $element)
{
return $array[$element];
}
$value = element($obj->getArray(), 4);
Also, see this question, as it is an exact duplicate: Any way to access array directly after method call?
I think you are doomed to do it that way :(
You can do this:
$res = array_pop(array_slice(somefunc(1), $i, 1));
If this is a one-off or occasional thing where the situation in your example holds true, and you're retrieving the first element of the return array, you can use:
$value = array_shift($obj->getArray());
If this is a pervasive need and you often need to retrieve elements other than the first (or last, for which you can use array_pop()), then I'd arrange to have a utility function available like so:
function elementOf($array, $index = 0) {
return $array[$index];
}
$value = elementOf($obj->getArray());
$otherValue = elementOf($obj->getArray(), 2);
Well, maybe this could help you, in php spl, pretty usefull, you can make you a Special Array for you:
<?php
class OArray extends ArrayObject{
public function __set($name, $val) {
$this[$name] = $val;
}
public function __get($name) {
return $this[$name];
}
}
class O{
function __construct(){
$this->array = new OArray();
$this->array[] = 1;
$this->array[] = 2;
$this->array[] = 3;
$this->array[] = 4;
}
function getArray(){
return $this->array;
}
}
$o = new O();
var_dump( $o->getArray()->{1} );
<?php
class MyArray implements Iterator ,ArrayAccess
{
private $var = array();
//-- ArrayAccess
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->var[] = $value;
} else {
$this->var[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->var[$offset]);
}
public function offsetUnset($offset) {
unset($this->var[$offset]);
}
public function offsetGet($offset) {
return isset($this->var[$offset]) ? $this->var[$offset] : null;
}//-- Iterator
public function __construct($array){
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
reset($this->var);
}
public function current() {
return current($this->var);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() !== false);
}
}
$values = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
$it = new MyArray($values);
foreach ($it as $a => $b) {
print "$a: $b<br>";
}
echo $it["one"]."<br>";?>