帮助一个类方法?

时间:2009-09-24 22:40:10

标签: php class

从下面的演示中你可以看到我正在尝试做什么,构造方法有效,但测试方法不起作用,给出了错误 致命错误:在非对象上调用成员函数get()

有人可以告诉我如何制作这样的作品吗?

<?PHP
//user.class.php file
class User
{
    public $pic_url;

    function __construct($session)
    {
        if($session->get('auto_id') != ''){
            $this->pic_url = $session->get('pic_url');
        }else{
            return false;
        }
    }

    function test($session)
    {
        return $this->pic_url = $session->get('pic_url');
    }
}

$user = new user($session);

//this works
echo $user->pic_url;

//this one does not work
echo $user->test();
?>

3 个答案:

答案 0 :(得分:2)

您没有向该函数提供$ session。

答案 1 :(得分:2)

  

//这个不起作用   $用户&GT;测试();

在没有参数的情况下调用函数应该抛出警告

Warning: Missing argument 1 for test(), called in ....

并且因为你试图访问那个没有传入test()的对象的函数,所以调用它也会抛出致命错误。

也可以将$ session参数传递给test()。

或者您可以尝试..

class User
{
    public $pic_url;
    private $class_session;

 public function __construct($session)
 {
     $this->class_session = $session;
     ... other code
 }
 function test()
    {
        return $this->pic_url = $this->class_session->get('pic_url');
    }
}

$user = new user($session);
echo $user->pic_url;
echo $user->test();

答案 2 :(得分:0)

试试这个:

<?php
//user.class.php file
class User
{
    public $pic_url;

    public function __construct($session)
    {
        if($session->get('auto_id') != ''){
                $this->pic_url = $session->get('pic_url');
        } else {
                return false;
        }
    }

    public function test($session)
    {
        if($this->pic_url == $session->get('pic_url')) {
            return $this->pic_url;
        } else {
            return 'test failed';
        }
    }
}

$user = new User($session);

//this works
echo $user->pic_url;

//this one does not work
echo $user->test();