Brian Coolidge
Brian Coolidge

Reputation: 4659

Run a function without a parameter but needed a variable outside of the function - PHP

I have this class called Campaign and I'm trying to echo $campaign->getName() without using any parameters like echo $campaign->getName($user_id, $campaign_id)

<?php 

$campaign = new Campaign($db);

class Campaign {

    private $db;

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

    public function getName() {

        $query = $this->db->prepare("SELECT name FROM campaign WHERE campaign_id = :campaign_id AND user_id = :user_id");
        $status = $query->execute(array(':campaign_id' => $campaign_id, ':user_id' => $user_id));
        return ($query->rowCount() == 1) ? $query->fetchObject()->name : false;
    }
}

What I'm getting is

Missing argument 1 for Campaign::getName()
Missing argument 2 for Campaign::getName()

Well logically thinking that's supposed to happen.

What I'm trying to call is $user_id and $campaign_id that's been retrieved at session

Here's the structure of my init.php where all the classes/functions are being stored.

enter image description here

Is it possible to call a function without a parameter, but that function needed a variable outside of the function?

Upvotes: 2

Views: 757

Answers (2)

Guns
Guns

Reputation: 2728

You havent called the $user_id and $campaign_id from session

Should have $user_id and $campaign_id as global variables:

global $user_id;
global $campaign_id;
$user_id = $_SESSION['user_id'];
$campaign_id = $_SESSION['campaign_id'];

Place the above variable declaration after session_start() on your screenshot

Try this:

<?php 

session_start();

$campaign = new Campaign($db);

class Campaign {

    private $db;

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

    public function getName() {

        $query = $this->db->prepare("SELECT name FROM campaign WHERE campaign_id = :campaign_id AND user_id = :user_id");
        $status = $query->execute(array(':campaign_id' => $_SESSION['campaign_id'], ':user_id' => $_SESSION['user_id']));
        return ($query->rowCount() == 1) ? $query->fetchObject()->name : false;
    }
}

Upvotes: -1

Rick Lancee
Rick Lancee

Reputation: 1659

You cannot access that variable since its only not defined locally inside the function.
If you want to use the var inside when its defined outside you use global before the var.

$foo = 'bar';
function baz() {
    global $foo;
    // now u can use it inside.
}

Php variable scope

I dont like globals personally, you could also do something like:

function foo($arg1 = null, $arg2 = null) {
    // if they are not set retrieve from a session
    $arg1 = ($arg1 !== null) ? $arg1 : $_SESSION['arg1'];
   // rinse repeat.
}

Upvotes: 2

Related Questions