PHP analog to C++ member pointers?

388

Does PHP have something similar to C++ member pointers? I want to use a member of a PHP object, whose name (the member'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;
534

Answer

Solution:

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

$var = 'foo';

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

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

901

Answer

Solution:

You can use variables in member calls.

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

Not sure if this will work for what you want.

111

Answer

Solution:

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";
793

Answer

Solution:

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.

989

Answer

Solution:

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

People are also looking for solutions to the problem: C# is to Visual Studio as PHP is to... anything?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.