Share variable between functions

I have a class for news items where I need to set certain variables which I need elsewere. The first function in the class is to determine the oldest news_id with status isNew = 1;:


function news_id(){
    $qry = "SELECT MIN(news_id) AS news_id
              FROM news
             WHERE isNew = 1";
			
    $stmt = $this->pdo->query($qry);
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $news_id = $row['news_id'];
    }
    return $news_id;	
}

I need the variable $news_id in several other functions in the same class, for example I need to determine the sender_id of a certain news item based on variable $news_id so I tried:


function sender_id($news_id){
    $qry = "SELECT sender_id
              FROM news
             WHERE news_id = $news_id";

    $stmt = $this->pdo->query($qry);
    $row  = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row['sender_id'];
}

But that gives me all kind of errors. What is the right way to use var $news_id in function sender_id()

Thank you in advance

I’m pretty sure that all you need to do is change

$news_id=$row['news_id'];

to

$this->news_id=$row['news_id'];

After that, always reference

$this->news_id

instead of

$news_id

.

As an alternative to @schizoman’s instance variable solution, just pass the id to your method:


$newsId = $repo->news_id();
$senderId = $repo->sender_id($newsId);

Whilst this in an alternative method, it would be far better to save the required value (as an instance variable) to prevent unnecessary round trips to the database for the same data.

Hmmm. Look closely at the original question and code. Two trips are required regardless.

I’m not too fond of the instance variable idea because you can’t really tell where it is being set from without digging into the code. Passing it as an argument makes it clear.

True, but that was only an example - he said multiple functions (including sender_id) require the return value provided by news_id. This means you’re having to make extra (unnecessary) trips to the database for data that you should already have.

I can’t say I’ve ever had that problem before since when I highlight a string in my editor, it auto-highlights all other instances of the same string (making it trivial to find where things like variables and functions are created and used).

It’s hard to say without seeing your code, but you shouldn’t just set an instance variable from a method and use that instance variable in other methods. This would imply that the code creating your object has to call that specific ‘news_id’ method before any other methods, which is weird. Either you set the ID in the constructor of that class OR you pass it all the time as a parameter. Depending from where this code is called, you don’t need to get the ID all the time from the database, only keep it in a variable or an object (like NewsConfig or whatever).

I have adjusted it in accordence to schizoman’s example:


        function get_news(){
            $qry = "SELECT MIN(news_id) AS news_id
                      FROM news
                     WHERE      isNew = 1";
			
            $stmt = $this->pdo->query($qry);
			while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
				$this->news_id = $row['news_id'];
			}
			return $this->news_id;	
        }
				
        function get_sender(){
			$news_id = $this->news_id; 
            $qry = "SELECT sender_id
                      FROM news
                     WHERE news_id = ?";

            $stmt = $this->pdo->prepare($qry);
			$stmt->execute(array($news_id));
            while($row = $stmt->fetch()) {
                $this->sender_id = $row['sender_id'];
			}
			return $this->sender_id;
        }

And it works great :). Thank you all a lot for the input and tips

So, you have to call get_news() before any other functions, which is not really a nice code design. If I read correctly, those functions are in a class. You should probably check how constructors work and set the news id there. It’s really easy, seriously :slight_smile:

Hi xMog. Thank you for the reply. Yes your have read it correctly, all functions are in a class. I have been reading your previous post (#7) as well, and have been looking into constructors. I am a bit confused though. In the original function I first run a query before I set $this->news_id;. How would I do that in a constuctor?

Thank you in advance

Simply invoke the news_id() function in the constructor, and assign its return value to an instance variable:


class ClassName
{
    private $newsID  = 0;
    // other fields

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

    // other class methods
}

Hi tpunt, thank you for the reply. I am still a bit confused about the difference between: $this->newsID and $this->news_id and how to invoke it in other functions or elsewhere.

Sorry for the ignorance but I am completely new to PDO

$this->news_id() is the method we are invoking (notice the parentheses at the end). $this->newsID is the field (notice the lack of parentheses) we are assigning the return value from the news_id() function to. To invoke a method in a class, you use the pseudo-variable $this (meaning the current object) along with the arrow operator (->) to point to call said method.

I’d advise you to go through a basic object-oriented tutorial (like this one) to help give you a better understanding of OOP.

Hi tpunt. Thanks for the reply, explanation and link. It is very much appreciated. I for sure gonna read that tutorial, It looked very interessting at first glance. So when I ned the news id i reffer to it as

$this->newsID, right?

Yes, that’s correct.