Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using onMissingMethod cannot access object variables

In CF10, I want to access a variable Test object using onMissingMethod function in TestHelper object, but I am getting an error.

Test.cfc

component  {

public Any function init(){
    instance = { x = 1 };
    return this;
}

public numeric function getX(){

    return instance.x;

}

}

TestHelper.cfc

component  {

public Any function init( ){
    variables.testObj = new Test();
    return this;
}

public any function onMissingMethod( required string missingMethodName, required struct missingMethodArguments ){

    var func = variables.testObj[ arguments.missingMethodName ];
    return func( argumentCollection = arguments.missingMethodArguments );

}

}

Calling the object

obj = new TestHelper();
writeOutput( obj.getX() );  //Element INSTANCE.X is undefined in VARIABLES

In CF10, this gives me an error that element X is undefined in instance. It doesn't seem to recognize the variable instance. I could explicitly define getX function in TestHelper, but I was hoping I could use the onMissingMethod function.

Am I misunderstanding how onMissingMethod supposed to work here? FWIW, the code works in Railo.

like image 377
user2943775 Avatar asked Nov 01 '22 05:11

user2943775


1 Answers

If I understand your issue, I'm surprised this code runs on Railo. I don't think it should.

The issue is with this code:

var func = variables.testObj[ arguments.missingMethodName ];
return func( argumentCollection = arguments.missingMethodArguments );

Here you are pulling the function getX() out of variables.testObj, and running it in the context of your TestHelper instance. And that object doesn't have a `variables.x. Hence the error.

You need to put your func reference into variables.testObj, not pull getX out of it. So like this:

var variables.testObj.func = variables.testObj[ arguments.missingMethodName ];
return variables.testObj.func( argumentCollection = arguments.missingMethodArguments );

That way you're running func() (your proxy to getX()) in the correct context, so it will see variabales.x.

Given this situation, there's no way this code should work on Railo (based on the info you've given us being all the relevant info, anyhow).

like image 53
Adam Cameron Avatar answered Nov 03 '22 00:11

Adam Cameron