是否有可能在PHP中使用指针?

时间:2013-11-23 05:30:54

标签: php pointers

所以我理解引用不是指针:http://php.net/manual/en/language.references.arent.php

问题是,是否可以在php中使用指针?

鉴于以下示例,我猜这是我们在处理对象时所做的事情:

class Entity
{
  public $attr;
}

class Filter
{
  public function filter(Entity $entity)
  {
    $entity->attr = trim($entity->attr);
  }
}

$entity = new Entity;
$entity->attr = '  foo  ';
$filter = new Filter;
$filter->filter($entity);
echo $entity->attr; // > 'foo', no white space

上面的示例是使用指针后面的指针还是仍在交换内存,就像使用引用一样?

修改

另一个例子:

以下内容:

class Entity
{
  public $attr;
}
$entity = new Entity;
$entity->attr = 1;
$entity->attr = 2;

C

中有类似内容
int* attr;
*attr = 1;
*attr = 2;

2 个答案:

答案 0 :(得分:3)

当您将一个对象作为参数传递给您的函数时,该变量本身会被复制,但它所指的属性指向原始对象的属性,即:

function test(Something $bar)
{
    $bar->y = 'a'; // will update $foo->y
    $bar = 123; // will not update $foo
}

$foo = new Something;
$foo->y = 'b';
test($foo);
// $foo->y == 'a';

在函数内部,内存引用看起来有点像这样:

$bar ---+
        +---> (object [ y => string('b') ])
$foo ---+

$bar = 123;之后,它看起来像这样:

$bar ---> int(123)

$foo ---> (object [ y => 'b' ])

答案 1 :(得分:1)

如果你问这一行

$entity->attr = trim($entity->attr);

$entity是新内存或旧内存的引用。它是旧内存(或指针)的引用

相关问题