質問

I've been reading answers on SO questioning the need for nested functions, but I still haven't figured out 1) why my code is erroneous and 2) how I can fix it to make what I wrote work OR change my script so it's more acceptable (to the parser but also to experienced developers). Let me mention that I am new to PHP OOP...

The idea is I want to use a function that I previously defined in a whole lot of other functions, so it'll save me rewriting the code each time.

Here's the faulty code, then, which throws a fatal error "Call to undefined function" pointing to the line in which I call selectMediaIds () within getMedia ()... (FYI I purposefully omitted the variable initialization, constructor, getters, setters, etc. to make my post more compact.)

<?php

class MediaManager {

private function selectMediaIds (MObject $object) {
    $medias = array ();
    $req = $this -> _db -> query ('SELECT media_idMedia FROM mObject_has_media WHERE mObject_idmObject = ' . $object -> id ());
    while ($data = $req -> fetch (PDO::FETCH_ASSOC)) {
        $medias[] = $data;
    }
    $req -> closeCursor ();
    return $medias;
}

public function getMedia (MObject $object) {
    $medias = array ();
    $mediaIds = selectMediaIds ($object);
    if ($mediaIds[0] != null) {
        foreach ($mediaIds as $id) {
            $req = $this -> _db -> query ('SELECT * FROM media WHERE idMedia = ' . $id);
            $req -> fetch ();
            $medias[] = $req;
            //$medias[] = new Media ($req);
        }
    return $medias;
    }
}}?>

Thank you for your answer!

役に立ちましたか?

解決

This is nothing to do with "nested" functions, and calling a function from another to reuse code is indeed the whole point of using functions in the first place.

Your problem is that selectMediaIds is not a global function, but a private method of the class MediaManager - it is "part of" that class, and can reference the current instance of the class under the magic variable $this.

In order to call such a method, you have to call it using the object->method notation, so you need to use $this->selectMediaIds($object). That tells PHP that you want to call selectMediaIds within that particular object $this, which you know is an instance of class MediaManager.

This is the same operation as you are using with your DB call when you write $req->fetch();

他のヒント

selectMediaIds is defined in a scope of class MediaManager. That's why it should be accesed as $this->selectMediaIds().

Invoking selectMediaIds without defining scope means that the scope is global, in which you definitely has no selectMediaIds function defined.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top