views:

71

answers:

4
<?php
class obj {
    var $primary_key;

    function obj($key = null){
        if(isset($key)){
            $this->primary_key = $key;
        }
        echo "primary_key: ".$this->primary_key."<br/>";

        $this->obj_id = 14;


        echo "obj_id: ".$this->obj_id."<br/>";

        $key  = $this->primary_key;

        echo "obj_id from primary_key string: ".$this->$key."<br/>";
    }
}
?>

Is there a way to get $this->primary_key value? Like $this->$this->primary_key?

A: 
$obj_a = new obj(5);
echo $obj_a->primary_key;       // prints '5'
thetaiko
+1  A: 

Well in order for that function to even be of any use, you would need to create a new class and set it to a variable, such as this:

$myclass = new obj(1);

Although that form of a constructor is only supported for backward compatibility (deprecated, you're really supposed to use __construct now), it should still run and set all your variables, which can be retrieved in the following way:

echo $myclass->primary_key; // the primary_key value
echo $myclass->obj_id; // the obj_id value

Edit: Also this line needs to be corrected to change the '$key' to 'primary_key' near the end. Putting '$key' there will not return anything because it would be sending '$this->1' which does not exist.

echo "obj_id from primary_key string: ".$this->primary_key."<br/>";
animuson
A: 

In your last line:

echo "obj_id from primary_key string: ".$key."<br/>";

or:

echo "obj_id from primary_key string: ".$this->$primary_key."<br/>";

Seriously, I still don't understand the utility of this code...

Roberto Aloi
A: 
Tomas
the line echo "obj_id from primary_key string: ".$this->$key."<br/>"; should look like echo "obj_id from primary_key string: ".$this->$this->primary_key."<br/>"; but that's not alowed.
Tomas