-3

I have a PHP class as follows:

Class ArrayStore{

static $storage = array();

public static set($key, $value){
  //set value
}

public static get($key){
  //return value
}

}

How I want to use:

ArrayStore::set('["id"]["name"]["last"]', 'php');
ArrayStore::get('["id"]["name"]["last"]'); //should return php

ArrayStore::set('["multi"]["array"]', 'works');
ArrayStore::get('["multi"]["array"]'); //should return works

Let me know if there is a better way of setting and getting a multidimensional array with reason.

Edit: I tried something like this:

<?php
$x = array(1=>'a');
$op="\$x"."[1]";
$value=eval("return ($op);");

echo $value;//prints a.
?>
1
  • The code you posted is not OOP but procedural programming (with global variables) under disguise. PHP already provides the ArrayObject class that works as an array. Use it! Commented Jun 14, 2017 at 11:46

1 Answer 1

0

From your logic you can do like this:

<?php
class ArrayStore{

static $storage = array();

public static function  set($key, $value){
  self::$storage[$key] = $value;
}

public static function  get($key){
  return self::$storage[$key];
}

}
ArrayStore::set('["id"]["name"]["last"]', 'php');
echo ArrayStore::get('["id"]["name"]["last"]'); //should return php
echo "<br>";
ArrayStore::set('["multi"]["array"]', 'works');
echo ArrayStore::get('["multi"]["array"]'); //should return works
Sign up to request clarification or add additional context in comments.

1 Comment

It returns the expected output. However, It is not storing the data like array('id' => array('name'=>array('last' => 'php')))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.