gpt4 book ai didi

PHP ArrayObject 内部工作原理

转载 作者:搜寻专家 更新时间:2023-10-31 21:15:45 24 4
gpt4 key购买 nike

我在哪里可以找到 ArrayObject 的完整源代码(PHP 格式)?

我不明白的是为什么在向 ArrayObject 添加元素时可以使用“箭头”,例如:

$a = new ArrayObject();
$a['arr'] = 'array data';
$a->prop = 'prop data'; //here it is

可以看到使用了$a->prop = 'prop data';

是否有任何神奇的方法或使用了什么,以及 PHP 如何知道例如 $a['prop']$a->prop 意味着相同? (在这种情况下)

最佳答案

是的,这很神奇,可以直接在 PHP 中完成。查看重载 http://www.php.net/manual/en/language.oop5.overloading.php

您可以在类中使用 __get()__set 来执行此操作。要使对象表现得像数组,您必须实现 http://www.php.net/manual/en/class.arrayaccess.php

这是我的示例代码:

<?php
class MyArrayObject implements Iterator, ArrayAccess, Countable
{
/** Location for overloaded data. */
private $_data = array();

public function __set($name, $value)
{
$this->_data[$name] = $value;
}

public function __get($name)
{
if (array_key_exists($name, $this->_data)) {
return $this->_data[$name];
}

$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}

/** As of PHP 5.1.0 */
public function __isset($name)
{
return isset($this->_data[$name]);
}

/** As of PHP 5.1.0 */
public function __unset($name)
{
unset($this->_data[$name]);
}

public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->_data[] = $value;
} else {
$this->_data[$offset] = $value;
}
}

public function offsetExists($offset) {
return isset($this->_data[$offset]);
}

public function offsetUnset($offset) {
unset($this->_data[$offset]);
}

public function offsetGet($offset) {
return isset($this->_data[$offset]) ? $this->_data[$offset] : null;
}
public function count(){
return count($this->_data);
}
public function current(){
return current($this->_data);
}
public function next(){
return next($this->_data);
}
public function key(){
return key($this->_data);
}
public function valid(){
return key($this->_data) !== null;
}
public function rewind(){
reset($this->_data);
}
}

代替 current($a)next($a) 使用 $a->current()$ a->下一步()

关于PHP ArrayObject 内部工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com