get variable value
<?php
class obj 开发者_如何学JAVA{
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
?
<?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/>";
}
}
?>
$aaa = new obj("obj_id");
i want to get $this->obj_id value, but i dont whant to use variable $key. This line $this->obj_id = 14; will be dynamic and i would't be able to know, if $this->obj_id will be named obj_id or something else like $this->banana, it would be desided by new obj("banana")
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/>";
$obj_a = new obj(5);
echo $obj_a->primary_key; // prints '5'
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...
精彩评论