0

I am made a class that is called SQL_Connection. The purpose of this class is to return a reference ($con) to the calling variable. Example: $conRef = new SQL_Connection(); Where $conRef would now be a reference of $con and not an instance of SQL_Connection(), if this is possible of course.

The construct function at the end does return $con;, I presume this may be the issue :/

Thanks.

2 Answers 2

3

Using new implies that you know the exact type of the object you want to construct. The pattern you want to use is a factory method, not a constructor. For example:

class SQL_Connection
{
    public static function create()
    {
        $con = new Other_SQL_Connection();
        return $con;
    }
}

Then invoke SQL_Connection::create() elsewhere to obtain the object reference.

Sign up to request clarification or add additional context in comments.

5 Comments

So essentially I cannot return the variable by just calling the class?
@MichaelMitchell You cannot "call a class." You can call a constructor, but not a class.
could you not just use the __construct() function, create a variable outside of it called $db, and return $this->db = new mysqli();? then instantiating of the class would return the DB?
@Ohgodwhy but from what I was able to understand from this, when you do $var = new Class(), $var cannot be something other than the instance?
@MichaelMitchell The return value of the __construct() function is ignored. In your example, $var will always be an object of type Class, if the constructor does not throw an exception.
-1

As I think constructor methods can't return anything

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.