La Interfaz ArrayAccess en PHP
La Interfaz ArrayAccess en PHP
Documentation
Get Involved
Help
Search
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
ArrayAccess::offsetExists
Throwable::__toString
Manual de PHP
Referencia del lenguaje
Interfaces y clases predefinidas
La interfaz ArrayAccess
(PHP 5 >= 5.0.0, PHP 7)
Introduccin
Interfaz para proporcionar acceso a objetos como arrays.
Sinopsis de la Interfaz
ArrayAccess {
/* Mtodos */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}
<?php
classobjimplementsArrayAccess{
private$contenedor=array();
publicfunction__construct(){
$this->contenedor=array(
"uno"=>1,
"dos"=>2,
"tres"=>3,
);
}
publicfunctionoffsetSet($offset,$valor){
if(is_null($offset)){
$this->contenedor[]=$valor;
}else{
$this->contenedor[$offset]=$valor;
}
}
publicfunctionoffsetExists($offset){
returnisset($this->contenedor[$offset]);
}
publicfunctionoffsetUnset($offset){
unset($this->contenedor[$offset]);
}
publicfunctionoffsetGet($offset){
returnisset($this->contenedor[$offset])?$this->contenedor[$offset]:null;
}
}
$obj=newobj;
var_dump(isset($obj["dos"]));
var_dump($obj["dos"]);
unset($obj["dos"]);
var_dump(isset($obj["dos"]));
$obj["dos"]="Unvalor";
var_dump($obj["dos"]);
$obj[]='Aadido1';
$obj[]='Aadido2';
$obj[]='Aadido3';
print_r($obj);
?>
Tabla de contenidos
ArrayAccess::offsetExists Comprobar si existe un ndice
ArrayAccess::offsetGet Offset para recuperar
ArrayAccess::offsetSet Asignar un valor al ndice esepecificado
ArrayAccess::offsetUnset Destruye un offset
add a note
/**
* ArrayAndObjectAccess
* Yes you can access class as array and the same time as object
*
* @author Yousef Ismaeil <[email protected]>
*/
/**
* Data
*
* @var array
* @access private
*/
private $data = [];
/**
* Get a data by key
*
* @param string The key data to retrieve
* @access public
*/
public function &__get ($key) {
return $this->data[$key];
}
/**
* Assigns a value to the specified data
*
* @param string The data key to assign the value to
* @param mixed The value to set
* @access public
*/
public function __set($key,$value) {
$this->data[$key] = $value;
}
/**
* Whether or not an data exists by key
*
* @param string An data key to check for
* @access public
* @return boolean
* @abstracting ArrayAccess
*/
public function __isset ($key) {
return isset($this->data[$key]);
}
/**
* Unsets an data by key
*
* @param string The key to unset
* @access public
*/
public function __unset($key) {
unset($this->data[$key]);
}
/**
* Assigns a value to the specified offset
*
* @param string The offset to assign the value to
* @param mixed The value to set
* @access public
* @abstracting ArrayAccess
*/
public function offsetSet($offset,$value) {
if (is_null($offset)) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
/**
* Whether or not an offset exists
*
* @param string An offset to check for
* @access public
* @return boolean
* @abstracting ArrayAccess
*/
public function offsetExists($offset) {
return isset($this->data[$offset]);
}
/**
* Unsets an offset
*
* @param string The offset to unset
* @access public
* @abstracting ArrayAccess
*/
public function offsetUnset($offset) {
if ($this->offsetExists($offset)) {
unset($this->data[$offset]);
}
}
/**
* Returns the value at specified offset
*
* @param string The offset to retrieve
* @access public
* @return mixed
* @abstracting ArrayAccess
*/
public function offsetGet($offset) {
return $this->offsetExists($offset) ? $this->data[$offset] : null;
}
?>
Usage
<?php
$foo = new ArrayAndObjectAccess();
// Set data as array and object
$foo->fname = 'Yousef';
$foo->lname = 'Ismaeil';
// Call as object
echo 'fname as object '.$foo->fname."\n";
// Call as array
echo 'lname as array '.$foo['lname']."\n";
// Reset as array
$foo['fname'] = 'Cliprz';
echo $foo['fname']."\n";
/** Outputs
fname as object Yousef
lname as array Ismaeil
Cliprz
*/
?>
up
down
12
jojor at gmx dot net
4 years ago
Conclusion: Type hints \ArrayAccess and array are not compatible.
<?php
}
}
Using reset($myArrayAccessObject) returns the first property from $myArrayAccessObject, not the first
item in the items array.
If you want to use the reset() method to return the first array item, then you can use the following
simple workaround:
<?php
class MyArrayAccessObject implements Iterator, ArrayAccess, Countable {
protected $first = null; //WARNING! Keep this always first.
protected $items = null;
private function supportReset() {
$this->first = reset($this->items); //Support reset().
}
// ...
public function offsetSet($offset, $value) {
if ($offset === null) {
$this->items[] = $value;
}
else {
$this->items[$offset] = $value;
}
$this->supportReset();
}
}
?>
Finally, call $this->supportReset() in the end of all methods that change the internal $items array,
such as in offsetSet(), offsetUnset() etc.
<?php
$firstArrayItem = reset($myArrayAccessObject);
?>
up
down
12
max at flashdroid dot com
6 years ago
Objects implementing ArrayAccess may return objects by references in PHP 5.3.0.
...
This base class allows you to get / set your object properties using the [] operator just like in
Javascript:
<?php
$var = 'hello';
$arr = array();
$arr[0] = $var;
$arr[1] = &$var;
$var = 'world';
var_dump($arr[0], $arr[1]);
// string(5) "hello"
// string(5) "world"
?>
<?php
class obj implements ArrayAccess {
$var = 'hello';
$obj = new obj();
$obj[0] = $var;
//$obj[1] = &$var; // Fatal error: Cannot assign by reference to overloaded object
$obj->offsetSetRef(1, $var); // the work around
$var = 'world';
var_dump($obj[0], $obj[1]);
// string(5) "hello"
// string(5) "world"
?>
up
down
1
jordistc at gmail dot com
6 months ago
You can use the array functions on a object of a class that implements ArrayAccess using the __invoke
magic method in this way:
<?php
class ArrayVar implements ArrayAccess
{
private $data = [];
$keys = array_keys($arrayar());
var_dump($keys);
// array (size=3)
// 0 => string 'one'
// 1 => string 'two'
// 2 => string 'three'
For example:
<?php
class TestArrayAccess implements ArrayAccess {
private $container = array();
// ArrayAccess methods
}
One way of being able to use array_push would be by adding a toArray() method (note the return value
is a reference).
<?php
class TestArrayAccess implements ArrayAccess {
private $container = array();
// ArrayAccess methods
<?php
$x = new MyArray() ;
$x[0] = 0 ;
$x[0]++ ; //error 'Indirect modification of overloaded element has no effect'
$x[0] += 1 ; // this works OK.
?>
up
down
-2
luc at s dot illi dot be
8 months ago
add a note