获取其他数据的函数和类

时间:2012-12-26 13:17:23

标签: php mysql function variables

好的,所以我试图从用户那里获取id,如果我输入$getid = '1'一切正常

require_once "../maincore.php";

$getid = '1';
class UploadHandler
{   
    protected $options;
    // ...

    function __construct($options=null, $getid = '1') {

        $this->options = array( 
            'script_url' => 'myfile/'.$getid.'/',

  // ...

如果我输入$getid = $userdata['user_id'] 或者我把一些东西放到像$myid = $userdata['user_id'];这样的课堂上并设置$getid = $myid 什么都行不通我很久以来一直在尝试很多stuf和案例。 红色教程和什么是私有函数等等

还尝试了私有$myid = $userdata['user_id'];和var $myid = $userdata['user_id'];

所以我只想获取$userdata['user_id']的数据,我无法让它工作。

2 个答案:

答案 0 :(得分:0)

在我看来,好像您正在尝试将全局变量指定为方法参数的默认值...此无法完成。这有很多原因,但现在最重要的是这与OOP的主要思想相矛盾:OOP的一点是你不需要多次编写你的代码,无论发生了什么:

class My_DB_Object
{
    private $_connection = null;
    public function __construct($dbType = 'mysql', array $loginParams = array())
    {
        switch(strtolower($dbType))
        {
            case 'mysql':
                return $this->constructMySQL($loginParams);
            case 'pgsql':
                return $this->constructPGSql($loginParams);
            case 'mssql':
                return $this->constructMSSQL($loginParams);
            default:
                throw new InvalidArgumentException($dbType.' is not supported, yet?');
        }
    }
    private function constructMySQL(array $loginParams)
    {
        //and so on...
    }
}

此对象可以在所有项目中使用,无论您要使用什么数据库,它都可能定义select方法,处理不同的方式查询各种数据库,而不必一次又一次地重写相同的查询......

无法保证您尝试分配为默认值的变量将被设置,或者在范围中:您可能会在另一个对象的成员函数内创建一个新实例,也可能在完全不同的名称空间中。

基本上:默认值是硬编码的。
一个文件包含 类定义或生成输出的代码,您的代码段似乎同时执行这两个操作。

您的代码应如下所示:

require_once('UploadHandler.php');//or look into __autload()
$uploadInstance = new UploadHandler(null, $userdata['user_id']);

UploadHandler.php文件应如下所示:

<?php
class UploadHandler
{
    protected $options = null;
    public function __construct (array $options = array(), $getid = '1')
    {//assuming $options should be an array
        $this->options = $options;
        $this->options['script_url'] = 'myfile/'.$getid.'/';
    }
}
//no closing ?> tag!

答案 1 :(得分:0)

你必须将数据传递给类或注入数据(另一个主题):

当你构建你的课时,你会告诉班级什么是值。

//some place in your code
$userdata = array(...some data from somewhere ...);
//$options is optional but at the beginning of the args so the 'null' is required
$class = new UploadHandler(null, $userdata['user_id']);

可选参数放在函数参数的末尾通常很有帮助:

class UploadHandler
{   
    protected $options;
    // ...

    // Required params first then optional params
    function __construct($getid ,$options=null) {

        $this->options = array( 
            'script_url' => 'myfile/'.$getid.'/',

然后你构建你的班级:

//some place in your code
$userdata = array(...some data from somewhere ...);
//$options is now optional and at the end so the default value will be 'null'
$class = new UploadHandler($userdata['user_id']);