PHP命令行调用类方法报错:未定义函数及$this使用错误
The errors you're hitting stem from misunderstanding how class methods work in PHP—you can’t call them like standalone functions, nor use $this without an existing object instance. Here’s how to fix this:
Option 1: Instantiate the class first
Since your test() method is a non-static public method, you need to create an instance of the DatasetTest class before invoking the method on that object.
Replace your command with this:
$ php -r 'require "DatasetTest.php"; $testInstance = new DatasetTest(); $testInstance->test();'
This creates a new DatasetTest object, then calls the test() method on it—you’ll see the "worked" output as expected.
Option 2: Make the method static (if applicable)
If your test() method doesn’t rely on any class properties or instance-specific logic, you can modify it to be static. This lets you call it directly using the class name, no instantiation needed.
Update your DatasetTest.php code to:
class DatasetTest { public static function test() { echo "worked"; } }
Then run this command:
$ php -r 'require "DatasetTest.php"; DatasetTest::test();'
Why your previous attempts failed:
- Calling
test()directly: PHP searches for a global function namedtest(), but your method is tied to theDatasetTestclass—so it can’t locate it. - Using
$this->test():$thisonly refers to the current object instance, and it’s only valid inside a class method. Outside of that context, there’s no object to reference, hence the error.
内容的提问来源于stack exchange,提问作者Paul Kendal

