在PHP类中定义条件变量

时间:2014-10-29 09:39:34

标签: php class oop variables conditional-statements

我根据本教程编写了一个用于连接PayPal的PHP类 - http://www.smashingmagazine.com/2011/09/05/getting-started-with-the-paypal-api/

使用硬编码凭据时效果很好,但我的管理界面允许我启用或禁用沙盒模式并输入沙箱和真实帐户的凭据。

我的问题是,这是我第一次涉足OOP,而且我在课堂上遇到条件语句。例如,我需要在一个类中执行此操作,并在类中提供$ endpoint;

if( $sandbox ) {
    $endpoint = 'https://api-3t.sandbox.paypal.com/nvp';
} else {
    $endpoint = 'https://api-3t.paypal.com/nvp';
}

2 个答案:

答案 0 :(得分:0)

<{1>} oop中的类变量被访问为 - $this->sandbox&amp; $this->endpoint。你应该先在课堂上定义它们。

public $sandbox;
public $endpoint;

答案 1 :(得分:0)

您应该在构造函数中声明变量,这样您就可以将变量设置在类的范围之外。

class Paypal(){

   protected $sandbox;

    public function __construct($sandbox) {
        $this->sandbox = $sandbox;
    }

    ....
    ....

    if($this->sandbox) {
      //do something
    }
    else {
      //do something else
    }

    ...
}

然后在您的脚本中执行以下操作:

<?php
include('/path/to/Paypal.php');

public function checkSandbox() {
    //check if sandbox is enabled or not
    if($enabled)
        return true;
    return false;
}    

$sandbox = checkSandbox();

$paypal = new Paypal($sandbox);
...
...