0

I am having some issues with my function which returns an array, I decided to try and use an OO approach to my php code and try to make a class with a few static functions since I decided I don't want to access it using an object. In my code, within the same class, I decided to make the following function:

public static function decideCategory($tweets) {

    $tweet = $tweets;

    if(in_array($tweet, self::$food)) {
        echo "\nOur " . $tweet . " is under food\n";
    } //if statements of the same nature below as well. 

}

Now, this function works in the sense that it does not throw an error where $food is definded as an array at the top. However, originally I simply had $food defined at the top as just a private static variable, and then I had the following function which I passed into the in_array.

public static function getFood()
    {
        self::$food = array("Wendys", "McDonalds", "Wendy's", "Chic Fil A", "Chic-Fil-a", "Burger", "TGI", "BBQ", "Grilling", "Wine", "Tasty", "Yum", "IHOP", "Pancakes", "Pizza", "Cake"
        ,"Baking");
        return self::$food;
    }

However, it would return an error saying that in_array expects an array value for its second argument, but that instead it sees that a null was passed instead. Why is that and how can I use methods to do my comparison rather than the variables themselvs. If this were Java this would be how I would do it, and as such I cannot see why php would have these issues as it appears to follow a similar logic with returns.

3
  • 1
    I strongly suspect this is an XY problem. What are you trying to do here? Commented Apr 14, 2017 at 18:56
  • 2
    If you wanted to use an OO approach, then why are you trying to avoid using an object? Commented Apr 14, 2017 at 18:58
  • Although using Statics is not exactly full on OO, it still accessing it from the class name rather than just calling the function Commented Apr 14, 2017 at 20:28

1 Answer 1

3

Yes it would error because until you call self::getFood() Self::$food is null if you have declared it as

static $food;

update your method as below

public static function decideCategory($tweets)
{
    $tweet = $tweets;
    $food = self::getFood();
    if(in_array($tweet, $food)) {
        echo "\nOur " . $tweet . " is under food\n";
    } //if statements of the same nature below as well. 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Or in_array($tweet, self::getFood())
well, I tried doing it like that originally, the self::getFood(), but it complained that it was null
@SomeStudent i have tried this gist.github.com/anonymous/9c82067e09479123b9c44dfa8b743257 and got no errors, can you try the same.

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.