-4
<?php
class database{
    private static $instance;
    public function __construct()
    {       
    }   
    static public function newinstance()
    {

        if(!self::$instance)
        {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function conn()
    {
    mysql_connect('localhost','root','') or die("database connection error".mysql_error());
    mysql_select_db('user') or die("cannot select db".mysql_error());

    }
    public function test()
    {
        echo "Public function test";
    }

}
$db=database::newinstance()->conn();
$db->test();

?>

When i rung this php file i got this error:Fatal error: Call to a member function test() on null , what could be the problem?Thank you!

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Rus Sergiu
  • 49
  • 2
  • 10
  • Because the connection to your data base have failed, and the $db=database::newinstance()->conn(); returned null.. – Mouaici_Med Mar 16 '17 at 19:04
  • 1. you created instance for only one function so you can't call another.2 when you are able to call other one anyhow then you will get deprecated version warning – Alive to die - Anant Mar 16 '17 at 19:05
  • Please [stop using mysql_ functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) as they have been removed from PHP – Machavity Mar 16 '17 at 19:09

3 Answers3

2

conn() doesn't return anything, so $db is never set to anything. Maybe you meant to do this?:

$db=database::newinstance();
$db->conn();
$db->test();
David
  • 208,112
  • 36
  • 198
  • 279
0

conn() method returns nothing, which you have assigned to $db. Try with:

$db = database::newinstance();
$db->conn();
$db->test();

or you can return $this in conn() method and use your syntax:

public function conn()
{
  mysql_connect('localhost','root','') or die("database connection error".mysql_error());
  mysql_select_db('user') or die("cannot select db".mysql_error());
  return $this;
}
hsz
  • 148,279
  • 62
  • 259
  • 315
0

try this ...

<?php
    class database{
        private static $instance;
        public function __construct()
        {       
        }   
        static public function newinstance()
        {

            if(!self::$instance)
            {
                self::$instance = new self();
            }
            return self::$instance;
        }
        public function conn()
        {
        mysql_connect('localhost','root','') or die("database connection error".mysql_error());
        mysql_select_db('user') or die("cannot select db".mysql_error());

        }
        public function test()
        {
            echo "Public function test";
        }

    }
    $db=database::newinstance();
    $db->conn();
    $db->test();

    ?>
Mouaici_Med
  • 390
  • 2
  • 19