1

I am trying to find the best way to use an instance of my connection inside a function, but I don't know if I should pass it in as a parameter of my function or use a global.

This is my code:

<?php require_once('class/connexion.php'); $cx = Connexion::getConnexion(); function get_customers(){ $query = "SELECT * FROM customers"; $select = $cx->prepare($query); $select->execute(); $result = $select->fetchAll(PDO::FETCH_ASSOC); return $result } get_customers(); ?> 
1
  • 4
    you should pass it in (ie, dependency injection) as that is considered the better practice by the community. globals are generally frowned upon. Commented Nov 16, 2016 at 18:08

1 Answer 1

3

Pass it as argument:

<?php require_once('class/connexion.php'); $cx = Connexion::getConnexion(); function get_customers($cx){ $query = "SELECT * FROM customers"; $select = $cx->prepare($query); $select->execute(); $result = $select->fetchAll(PDO::FETCH_ASSOC); return $result } get_customers($cx); ?> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.