$instance = new className();
$instance["name"]
Come farlo funzionare, un esempio?
risposte:
5 per risposta № 1Se la tua classe implementa SPL ArrayAccess di PHP, quindi sarai in grado di fare riferimento agli attributi della classe nel modo che descrivi.
Tratto dal tutorial che ho collegato:
class book implements ArrayAccess {
public $title;
public $author;
public $isbn;
public function offsetExists($offset) {
return isset($this->$offset);
}
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
public function offsetGet($offset) {
return $this->$offset;
}
public function offsetUnset($offset) {
unset($this->$offset);
}
}
/*** a new class instance ***/
$book = new book;
/*** set some book properties ***/
$book["title"]= "Pro PHP";
$book["author"] = "Kevin McArthur";
$book["isbn"] = 1590598199;
print_r($book);
3 per risposta № 2
$instance->name
se si desidera convertire l'oggetto in un array, è possibile verificare Questo.
2 per risposta № 3
Dipende da come hai definito le variabili del tuo membro, normalmente puoi accedervi in questo modo a meno che non siano pubbliche:
$instance = new className();
$instance->name;
Se tuttavia lo hai definito come variabile statica, devi accedervi in questo modo:
$instance = new className();
$instance::$name;
Se intendevi ottenere variabili come questa (come array):
$instance = new className();
$instance["name"] // <----------- won"t be like that exactly
Devi definire un array nella tua classe:
class myclass
{
public $myarray = array();
// more stuff to fill that array
}
Ora puoi accedervi in questo modo:
$instance = new className();
$instance->myarray["name"];
Ma non ancora così:
$instance = new className();
$instance["name"]
2 per risposta № 4
Il tuo oggetto deve essere implementato ArrayAccess. Se si desidera poter accedere solo alle proprietà pubbliche (variabili di classe), sarà necessario utilizzare anche ReflectionClass per controllare i modificatori di accesso sulla proprietà.
1 per risposta № 5
cast l'oggetto come array
$instance = new className();
$arrayinstance=(array)$instance ;
$arrayinstance["name"] is the same as $instance->name
non sono sicuro se fosse la domanda esatta fatta ....