kalaba2003
kalaba2003

Reputation: 1229

Is the use of "function $var() { }" true in php?

I'm using codeigniter and in controller folder, I created a php file like :
NOTE: connects database automaticly.

<?php

    class Book extends CI_Controller {

        $query = $this->db->get('books');

        foreach ($query->result() as $row) {

            function $row->book_name() {
                echo $row->book_name;
            }

        }

    }

?>

I tried to create functions by fetching book names from the database but I can not. By using $variable in function name, is it possible to create function? If not, How can create it in a quick way? Thanks...

Upvotes: 0

Views: 103

Answers (3)

drew010
drew010

Reputation: 69967

I think you may be interested in __call().

If a call is made to a method in a class that does not exist, the __call() method is invoked and you can handle the call from there.

Store the books in an array as you read the results, and add a __call method to your class. When the method is accessed, you can search the array for the book based on the name of the function called and act appropriately.

class Book extends CI_Controller {
    protected $_books = array();

    public function __construct() {
        $query = $this->db->get('books');

        foreach ($query->result() as $row) {
            $this->_books[] = $row->book_name;
        }
    }

    public function __call($name, $arguments) {
        if (in_array($name, $this->_books)) {
            echo $name;
        } else {
            ehco 'I do not have this book!';
        }
    }
}

Just keep in mind PHP's rules for naming methods, a valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. No spaces are allowed so keep that in mind.

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

Absolutely.

$myfunction = function($a,$b,$c) {return $a+$b+$c;};

This is an example of an anonymous function. It has no name, but it can be accessed by $myfunction(1,2,3).

I'm not entirely sure what you're trying to do in your example... Should just echo $row->book_name alone be enough? Or are you trying to define a function with the same name as a book? In the latter case, you can use variable variables: ${$row->book_name} = function... - it's probably not a good idea though.

Upvotes: 4

Nurickan
Nurickan

Reputation: 304

Is it create_function() that you are searching for?

But seriously, it took me a minute to google it..

Upvotes: 0

Related Questions