0

I have a class that for the sake of example to make it easier to understand, takes an associative array, loops over it and assigns a variable name, based on key, and assigns it the value. This works fine in the class:

class showItems {

  static public function list(){
    foreach ($list as $name => $value) {
      $$name = $value;
    }
    // This works here
    echo $title; // This is the variable I want Which is being set in the foreach.
    break;

  }

}

The above class works fine, and $title can be echo'd. However, accessing that variable from outside of the class is where I don't have any luck. I've tried all types of processes I can think of.

$showItems = new showItems();
$showItems::list();

// Cannot grasp what I need to do here to echo the value I want.
$showItems::list()->$title; // This returns "Trying to get property of non-object"

?>
1
  • What does function showItems return? Commented Jun 28, 2014 at 17:35

2 Answers 2

1
  1. Don't echo inside your list method.

  2. You can reach your static list method through your class like this: showItems::list()

  3. You are not passing a parameter to your list method, which is highly strange, as you have stated that it

takes an associative array

  1. Your $list seems to be uninitialized inside your list method.

  2. No need to instantiate your class if you only want to call a static method.

  3. It is unclear what you are trying to do, so please, rephrase your question and write a comment to this post, so I will edit my answer to help you further.

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

2 Comments

It's quite clear, inside the foreach loop running inside the class, I can echo $title, so I know it's working, don't worry about the rest of the code. However - how do I actually retrieve that $title variable from outside of the class?
You can create a static member called $title inside your showItems class and create a getter for it. However, if something seemingly "works", that is not necessarily correct.
1

Do something like $TestItems=new testItems() then TestItems->list() and make the list function return $title.

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.