【问题标题】:any way to add new method to an object in php such as javascript?有什么方法可以向 php 中的对象(例如 javascript)添加新方法?
【发布时间】:2014-06-21 11:30:34
【问题描述】:

有什么方法可以在 php 中为对象添加新方法,例如 javascript?

在javascript中我们可以像这样扩展一个js obj

var o={};
o.test1 = function(){...}

如何在php中做到这一点?请在下面查看我的代码:

<?php

class a{
    function test(){
        echo 'hello';
    }
}

$var= new a;

// I want to add a new method fo $var
// .... how to extend $var here ?

$var->test1();  // world

// placeholder
// placeholder
// placeholder
// placeholder
// placeholder
// placeholder
// placeholder

【问题讨论】:

  • 我必须评论说,在 PHP 中这样做是没有意义的。在大多数情况下,动态添加方法只是简单的愚蠢。但是,您可以通过使用 PHP 的魔法 __call 方法,或者使用名为 classkit 的 PHP 扩展来动态定义方法。但是,你真的应该重新考虑你的应用程序设计,并完全避免需要提到的功能(当然,如果没有它,你可能根本无法做到,所以我的评论也可能是纯粹的废话)。

标签: php


【解决方案1】:

你可以扩展你的对象:(注意:这不是我的代码,我只是复制这个代码是从文档 php 扩展类)

<?php

class foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }

    public function printPHP()
    {
        echo 'PHP est super' . PHP_EOL;
    }
}

class bar extends foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Affiche : 'Foo: baz'
$foo->printPHP();       // Affiche : 'PHP est super'
$bar->printItem('baz'); // Affiche : 'Bar: baz'
$bar->printPHP();       // Affiche : 'PHP est super'

?>

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2014-12-22
    • 2010-12-25
    相关资源
    最近更新 更多