You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP命令行调用类方法报错:未定义函数及$this使用错误

Correct Ways to Call Your Class Method in PHP Command Line

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 named test(), but your method is tied to the DatasetTest class—so it can’t locate it.
  • Using $this->test(): $this only 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:55:39