3

before I ask my question, I would like to say that I searched for this question, and none of the other answers helped...

Basically, in my class DemoClass, I have 4 functions, and all of them are "undefined properties"

My error:

Notice: Undefined property: DemoClass::$function in /home/content/92/10270192/html/class.php on line 46

Note: line 46 is where i do $demoClass->function...

I have a typical class setup:

class DemoClass {
    public function __construct () {
        // stuff that works and gets called
    }
    public function testFunct () {
        // one that is an "undefined property"
    }
}

I access the class as normal:

$testClass = new DemoClass();
var_dump(testClass->testFunct); // this is what is on line 46
// ^^^ This also gives me NULL, because its undefined (? i guess...)

I've never had this problem before, any suggestions? Thanks!

4 Answers 4

13

Brackets are required when calling a function. Change it to $testClass->testFunct() instead.

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

2 Comments

My apologizes - that is a typo in the question, I have it correct in my implementation...
Should be $testClass (dollar-sign prefix)
2

$testClass->testFunct references a variable testFunct in the class. You need to use $testClass->testFunct() to reference a function in the class.

2 Comments

Am I that dumb? Wait... yes I am - thanks! I need some sleep ;)
Get to bed before you break any more of your code, then come back refreshed! :-)
1

It should be

var_dump(testClass->testFunct())

A function always needs the parentheses as else (as you can see) you can't tell the difference between a function and a constant.

Comments

0

Unlike for instance JavaScript, PHP is not handling class methods as regular properties.

When you use $testClass->testFunct, PHP looks for a property named testFunct and finds none.

Methods can be referenced through class name, DemoClass::testFunct in your case.

2 Comments

Note: accessing methods via class name, like DemoClass::testFunct requires the method to be static.
Well technically you can access it, but trying to invoke it will end up in tears (which makes this access of very limited use indeed).

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.