可能是一个新手问题,但后来我正在学习:
在下面的代码中,我需要命名$ targetname和$ imagelocation来自$ _POST变量......我知道我不能按照我想要的方式正确定义这些变量,但是我有点难过...帮助任何人?
class PostNewTarget{
//Server Keys
private $access_key = "123456";
private $secret_key = "142356";
private $targetName = $_POST['the_target'];
private $imageLocation = $_POST['the_image'];
function PostNewTarget(){
$this->jsonRequestObject = json_encode( array( 'width'=>300, 'name'=>$this->targetName , 'image'=>$this->getImageAsBase64() , 'application_metadata'=>base64_encode($_POST['myfile']) , 'active_flag'=>1 ) );
$this->execPostNewTarget();
}
...
答案 0 :(得分:3)
进入方法:
function PostNewTarget($targetName, $imageLocation)
然后致电:
PostNewTarget($_POST['the_target'], $_POST['the_image'])
您可以添加构造函数,但我不会:
public function __construct() {
$this->targetName = $_POST['the_target'];
$this->imageLocation = $_POST['the_image'];
}
答案 1 :(得分:1)
您需要首先初始化您的类属性
使用构造函数创建类对象时,可以将$ _POST值设置为类属性,或者可以在需要获取这些值时设置,我在示例中进行了设置
class PostNewTarget{
//Server Keys
private $access_key = "123456";
private $secret_key = "142356";
private $targetName = "";
private $imageLocation = "";
//you can give class variables values in the constructor
//so it'll be setted right when object creation
function __construct($n){
$this->targetName = $_POST['the_target'];
$this->imageLocation = $_POST['the_image'];
}
function PostNewTarget(){
//or you set just only when you need values
$this->targetName = $_POST['the_target'];
$this->imageLocation = $_POST['the_image'];
$this->jsonRequestObject = json_encode( array( 'width'=>300, 'name'=>$this->targetName , 'image'=>$this->getImageAsBase64() , 'application_metadata'=>base64_encode($_POST['myfile']) , 'active_flag'=>1 ) );
$this->execPostNewTarget();
}
}
答案 2 :(得分:1)
将其视为普通变量,并将其置于函数的构造函数或mutator或参数中(如果仅在该函数中需要它)。这是一个使用构造函数的示例,但逻辑在每种情况下都是相同的。
class Example {
public $varFromPOST;
public $name
public function __construct($var, $name) {
$this->varFromPOST = $var
$this->name = $name
}
}
然后在你的index.php中:
$_POST['foo'] = 100;
$userName = 'Bob';
$Example = new Example($_POST['foo'], $userName);
如果我没有误解你的问题,似乎很简单。