【问题标题】:Defining conditional variables in a PHP class在 PHP 类中定义条件变量
【发布时间】:2014-10-29 09:39:34
【问题描述】:

我已经根据本教程编写了一个用于连接到 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';
}

【问题讨论】:

  • 你是如何定义变量的??

标签: php class oop variables conditional-statements


【解决方案1】:

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

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

【讨论】:

  • 谢谢尼古拉斯。如果可能的话,我宁愿在类中定义 $endpoint 和 $sandbox,因为我不想在每次创建新实例时都定义它们。
  • @chips 根据我对您问题的理解,您至少需要在类之外声明 $sandbox,因为无法从类内部知道它是否已启用。因此,您可以从构造函数中省略 $endpoint 变量,但 $sandbox 需要保留。类不是程序化的,它们无法判断某些内容是否已被检查或未检查。
  • @chips 我也调整了答案
  • 再次感谢 Nicholas 突然间一切都到位了,我不知道在课堂上不可能进行过程编码!在这种情况下,是否可以从定义变量的类中调用一个函数,或者我是否必须执行类似 $paypal = new Paypal( $myfunction );
  • 如果函数在另一个类中定义是可能的,但是您需要将另一个类导入您当前的 Paypal 类。在您的实例中,让 $sandbox 等于简单函数的返回值要容易得多。看上面的改动^_^
【解决方案2】:

oop 中,类变量的访问方式类似于-$this-&gt;sandbox$this-&gt;endpoint。你应该首先在课堂上定义它们。

public $sandbox;
public $endpoint;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    相关资源
    最近更新 更多