-1

I am trying to simply call a class function and this error keeps on bugging me

syntax error, unexpected '$db' (T_VARIABLE), expecting function (T_FUNCTION)

database.php

<?php
    class db
    {
        public static Somefunction($pr1, $pr2)
        {
            // SOME CODE HERE
        }
    }
?>

dtCall.php

<?php
    require_once "database.php";
    class database
    {
        $db = new db();

        public function myFun()
        {
            $result = $db->Somefunction($pr1, $pr2);
        }
    }
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
TanvirDuggal
  • 37
  • 1
  • 8
  • You cannot set class variables with a function, only with non-dynamic values (strings, numbers, null or boolean). You'll have to that in a constructor. – aynber Oct 15 '18 at 14:16

2 Answers2

2

This might help you on your way:

<?php
//require_once "database.php";

class db
{
    public function __construct()
    {
    }

    public static function Somefunction($pr1 = null, $pr2 = null) // you forgot to declare a 'function'
    {
        echo 'hello from db';
    }
}

class database
{
    public $db = null;

    public function __construct()
    {
        $this->db = new db();
    }

    public function myFun()
    {
        $result = $this->db->Somefunction($pr1 = null, $pr2 = null);
    }
}

$invoke = new database();
$invoke->db->Somefunction();
lovelace
  • 1,195
  • 1
  • 7
  • 10
-1

This is occurring because you need to specify whether or not $db is public, protected, or private. Simply add public, private, or 'protected' in front of the variable declaration:

<?php
    require_once "database.php";
    class database
    {
        public $db = new db();   #<== Add to this line 

        public function myFun()
        {
            $result = $db->Somefunction($pr1, $pr2);
        }
    }
?>

If you are unsure of which to use, check out this post: What is the difference between public, private, and protected?

Upon fixing this, you will get a new error. That is because class constants must be constant. Check out the PHP documentation for more information: http://php.net/manual/en/language.oop5.constants.php

Sara Fuerst
  • 5,688
  • 8
  • 43
  • 86
  • `This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.` [source](http://php.net/manual/en/language.oop5.properties.php) – aynber Oct 15 '18 at 14:23
  • Hii I did and got a new error "PHP Fatal error: Constant expression contains invalid operations in dtCall.php on line 16", (its the same line as I changed)... – TanvirDuggal Oct 15 '18 at 14:24
  • That is because of what is mentioned by @aynber. The constant must be a constant value – Sara Fuerst Oct 15 '18 at 14:26
  • @aynber yes, that is true. I've updated the answer to include that – Sara Fuerst Oct 15 '18 at 14:37