如何从两个源之一设置对象的值

  • 本文关键字:设置 对象 两个 php oop
  • 更新时间 :
  • 英文 :


现在我正试图解决处理数据的问题,a)来自Facebook Graph API或b)通过表单提交手动提供的用户。为了简单起见,下面是我目前设置类的方式,不考虑手动表单提交:

class user {
public $collegemajor;
public function __construct($collegemajor)
$this->collegemajor = $collegemajor;
$collegemajor = isset($user_profile['education'][0]['concentration'][0]['name']) ? $user_profile['education'][0]['concentration'][0]['name'] : null ;
$objUser = new user ($collegemajor);
}

这大概是我要做的。请记住,我还没有在应用程序中使用getter或setter方法。目标是设置$ collegemmajor作为图形API值,如果它可用,或者如果API数据不可用,则作为发布的表单提交。假设数据无法从API获得,则用户已经提交了major via表单。最好的方法是什么?它是getter和setter方法吗?如果是这样,我就不知道该如何构建它了。将它添加到这一行如何:

$collegemajor = isset($user_profile['education'][0]['concentration'][0]['name']) ? $user_profile['education'][0]['concentration'][0]['name'] : null ;

表单提交的值,如果存在的话,应该是这样的:

$_POST['major'];

下面是我失败的尝试。它没有按照计划返回表单提交的值。如有任何帮助,不胜感激:

class user {
public $collegemajor;
public function __set($collegemajor, $value) {
        if (isset($this->collegemajor)) {
            return $this->collegemajor;
        } else {
            return $_POST['major'];
        }
    }
public function __construct($collegemajor) {
$this->collegemajor = $collegemajor;
}
public function echos () {
    echo "$this->collegemajor";
    }
}
?>

您的对象试图承担比它应该承担的更多的责任。您的user对象应该只管理属于给定用户的数据,它不应该尝试实现获取该数据的各种方法。

正确的方法是让一个类从源获取数据,并以标准化格式呈现给用户类使用。这样就将管理用户的任务与向用户类中获取数据的任务分开了,这被认为是更好的OOP实践。

最新更新