开发者

PHP analog to C++ member pointers?

开发者 https://www.devze.com 2023-02-04 10:46 出处:网络
Does PHP have something similar to C++ member pointers? I want to use a member of a PHP object, whose name (the member开发者_如何学Python\'s, not the object\'s) I only know at runtime. For example:

Does PHP have something similar to C++ member pointers? I want to use a member of a PHP object, whose name (the member开发者_如何学Python's, not the object's) I only know at runtime. For example:

$object = new stdClass();
$object->NewMember = "value";

$member = 'NewMember';
// I don't know whether this is valid PHP,
// but you get what I'm trying to do.
echo $object->$member;


<?php
class Test
{
    public $foo = 'bar';
}

$var = 'foo';

$test = new Test();
echo $test->$var;

Edit: after your update, yes, that will work.


You can use variables in member calls.

$methodName = 'some_method';
$myObj->$methodName($param);

Not sure if this will work for what you want.


In the following code I'm setting the $memberToGet at runtime:

class Person
{
  public $foo = 'default-foo';
  public $bar = 'default-bar';
}

$p = new Person();

$memberToGet = 'foo';
print "The Person's $memberToGet is [" . $p->$memberToGet . "]\n";

$memberToGet = 'bar';
print "The Person's $memberToGet is [" . $p->$memberToGet . "]\n";


No, PHP doesn't support (member) pointers. However you could use Reflection API.

class MyClass {
    public function doSth($arg1, $arg2) { ... }

    public static function doSthElse($arg1) { ... }
}

$ref = new ReflectionMethod('MyClass', 'doSth');
$ref->invokeArgs(new MyClass(), array('arg1', 'arg2'));

$ref = new ReflectionMethod('MyClass', 'doSthElse');
$ref->invokeArgs(null, array('arg1'));

As you can see in other answers you could also write:

class MyClass { ... }

$method = 'doSth';

$obj = new MyClass();
$obj->$method('arg1', 'arg2');

But I really don't recommend that way. It's tricky, obscure and much harder to debug and maintain.


By passing $this as a variable by reference, you can access members of that class.

0

精彩评论

暂无评论...
验证码 换一张
取 消