Bir sınıf yöntemi ile yardım?

3 Cevap php

From the demo below you can probably see what I am trying to do, the construct method works but the test method does not work, gives error Fatal error: Call to a member function get() on a non-object

Birisi nasıl bu iş böyle bir şey yapmak bana gösterebilir misin?

<?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 Cevap

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

Bir argüman olmadan burada bir işlevi çağıran bir uyarı atmak gerekir

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

ve testi geçemiyor o nesnenin bir işleve erişmek için çalışıyoruz, çünkü () onun yanı sıra bir Ölümcül hata atma diyoruz.

Gibi iyi test etmek için $ session argümanını () geçmek.

OR you can try ..

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

Sen işlevine $ oturumu temin değiliz.

Bu deneyin:

<?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();