0

可能是一个新手问题,但后来我正在学习:

在下面的代码中,我需要命名 $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();

}
...
4

3 回答 3

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'];
}
于 2013-11-06T00:07:33.667 回答
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();

} 
}
于 2013-11-06T00:12:17.993 回答
1

如果仅在该函数中需要它,则将其视为普通变量并将其放入函数的构造函数或修改器或参数中。这是一个使用构造函数的示例,但每种情况下的逻辑都是相同的。

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);

看起来很简单,如果我没有误解你的问题。

于 2013-11-06T00:12:58.650 回答