-1

My PHP class function looks something like as when fetching data from database table:

class my {
   public $a;

   public function myFunc(){
       $query = mysql_query("select name,loc,info from stores");
       while ($row = mysql_fetch_array($query)) {
           extract($row);
            echo $this->a;
       }
   }
}

I want that it should print the result of that rows of table which are called when creating object of the class and calling class method as:

$class = new my();
$class->a = '<h1>$name</h1>';
$class->a .= '<p>$loc</p>';
$class->myFunc();

But it did't gives proper result and print as:

$name
$loc
$name
$loc
$name
$loc
...

I want it should print the values of these variable which are actually rows of table and result should be something looking like as:

london store
london near the big mall, england
PK world wide store
F-5 street near the new G-T road london
...

How it can be possible?

Thank You.

Syed Aqeel
  • 1,009
  • 2
  • 13
  • 36
  • Possible duplicate of [PHP OOP print a variable which has value inside the function but call from outside to be print](http://stackoverflow.com/questions/38023628/php-oop-print-a-variable-which-has-value-inside-the-function-but-call-from-outsi) – mferly Jun 25 '16 at 01:38

1 Answers1

0

'<h1>$name</h1>' and '<p>$loc</p>' are just a plain strings. The variable references inside them won't get evaluated by echo.

You can return the items and render them outside of the function:

class my {
   public function myFunc(){
       $query = mysql_query("select name,loc,info from stores");

       $items = array();
       while ($row = mysql_fetch_array($query)) {
            $items[] = $row;
       }

       return $items;
   }
}

$class = new my();
$items = $class->myFunc();

foreach ($items as $item) {
    echo "<h1>{$item['name']}</h1><p>{$item['loc']}</p>";
}

If you insist on rendering from within the function you can pass in an anonymous function:

class my {
    public $renderer; 

    public function myFunc(){
        $query = mysql_query("select name,loc,info from stores");

        while ($row = mysql_fetch_array($query)) {
             call_user_func($this->renderer, $row);
        }
    }
}

$class = new my();

$class->renderer = function ($row) {
    extract($row);
    echo "<h1>$name</h1><p>$loc</p>";
};

$class->myFunc();

I've used double quoted strings in the code. See PHP docs to learn the difference or see What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
Shira
  • 6,392
  • 2
  • 25
  • 27