标签: magic-methods

__callStatic(),call_user_func_array(),引用和PHP 5.3.1

我一直在阅读SO和其他地方,但我似乎无法找到任何结论.

有没有办法通过此调用堆栈有效地携带引用,从而产生所需的功能,如下面的示例所述?虽然该示例并未尝试解决此问题,但它确实说明了问题:

class TestClass{
    // surely __call would result similarly
    public static function __callStatic($function, $arguments){
        return call_user_func_array($function, $arguments);
    }
}

// note argument by reference
function testFunction(&$arg){
    $arg .= 'bar';
}

$test = 'foo';
TestClass::testFunction($test);

// expecting: 'foobar'
// getting:   'foo' and a warning about the reference
echo $test;
Run Code Online (Sandbox Code Playgroud)

为了激发潜在的解决方案,我将在此处添加摘要详细信息:

只关注call_user_func_array(),我们可以确定(至少在PHP 5.3.1中)你不能通过引用隐式传递参数:

function testFunction(&$arg){
    $arg .= 'bar';
}

$test = 'foo';
call_user_func_array('testFunction', array($test));
var_dump($test);
// string(3) "foo" and a warning about the non-reference parameter
Run Code Online (Sandbox Code Playgroud)

通过显式传递数组元素$test …

php pass-by-reference magic-methods dynamic-function

8
推荐指数
1
解决办法
5637
查看次数

用户定义的魔术方法:什么是"记录的魔术功能"?

我的问题很简单,这里是上下文:

http://php.net/manual/en/language.oop5.magic.php

魔术方法

函数名__construct(),__destruct(),__call(), __callStatic(),__get(),__set(),__isset(),__unset(),__sleep(),__wakeup(),__toString(),__invoke(),__set_state()和__clone()在PHP类魔法.除非您想要与它们相关联的魔术功能,否则您不能在任何类中使用这些名称的函数.

PHP保留所有以__开头的函数名称作为魔法.除非您需要一些记录的魔术功能,否则建议您不要在PHP中使用带__的函数名.

我得到了这些方法的用途以及如何使用它们.我不明白的是:

...除非你想要一些记录的魔术功能.

那有什么意思?是否有创建用户定义的实际原因__magicMethods()

php magic-methods

8
推荐指数
1
解决办法
1396
查看次数

通过__call实现通知接口方法?

我有一个接口,声明实现需要的方法,如find,findOrFail等,基本上是Laravel雄辩的方法.

我在接口中声明了这些方法,因为并非所有实现接口的方法都会扩展,所以我在接口中声明它们,所以我的应用程序总是知道方法会在那里.

我想知道的是,除了具有一堆其他public function find($id){return parent::find($id)}的车型类型的方法是不要延长雄辩模型有一种简单的方法,让界面知道该方法是通过处理__call

php inheritance interface magic-methods laravel

8
推荐指数
2
解决办法
2669
查看次数

使用__call和静态类?

__call在静态调用函数时是否可以使用魔术方法?

php oop static magic-methods

7
推荐指数
2
解决办法
6480
查看次数

Php __get和__set魔术方法 - 为什么我们需要这些?

在Zend快速入门指南http://framework.zend.com/manual/en/learning.quickstart.create-model.html上我们可以看到:

class Application_Model_Guestbook
{
    protected $_comment;
    protected $_created;
    protected $_email;
    protected $_id;

    public function __set($name, $value);
    public function __get($name);


    public function setComment($text);
    public function getComment();
...
Run Code Online (Sandbox Code Playgroud)

我通常在没有任何魔术方法的情况下创建我的getter和setter.我在快速指南上看过这个,我不明白为什么我们需要这个.

谁能帮我吗?

非常感谢

php zend-framework magic-methods

7
推荐指数
2
解决办法
3232
查看次数

Numpy __getitem__延迟评估和[-1:]与[slice(-1,None,none)]不一样

所以这是关于我所假设的两个问题,就是我的基本混淆.我希望没关系.

这里有一些代码:

import numpy as np

class new_array(np.ndarray):

    def __new__(cls, array, foo):
        obj = array.view(cls)
        obj.foo = foo
        return obj

    def __array_finalize__(self, obj):
        print "__array_finalize"
        if obj is None: return
        self.foo = getattr(obj, 'foo', None)

    def __getitem__(self, key):
        print "__getitem__"
        print "key is %s"%repr(key)
        print "self.foo is %d, self.view(np.ndarray) is %s"%(
            self.foo,
            repr(self.view(np.ndarray))
            )
        self.foo += 1
        return super(new_array, self).__getitem__(key)

print "Block 1"
print "Object construction calls"
base_array = np.arange(20).reshape(4,5)
print "base_array is %s"%repr(base_array)
p = new_array(base_array, 0)
print "\n\n" …
Run Code Online (Sandbox Code Playgroud)

python numpy magic-methods

7
推荐指数
1
解决办法
864
查看次数

如何在Python3文件中打印__repr__?(不在外壳中)

我知道在 Python Shell 中,当您键入时,>>> object它会显示该object.__repr__方法,如果您键入,>>> print(object)它也会显示该object.__str__方法。

但我的问题是,有没有一种__repr__在执行Python文件时进行打印的简短方法?

我的意思是,在 file.py 中,如果我使用print(object)它,它会显示object.__str__,如果我只是键入,object它不会显示任何内容。

我尝试过使用print(object.__repr__)但它打印<bound method object.__repr__ of reprReturnValue>

或者这是不可能的?

python shell repr magic-methods

7
推荐指数
1
解决办法
6513
查看次数

Python中有sorted()的神奇方法吗?

我知道Python中有一些神奇的方法可以被类覆盖,以控制某些内置函数处理这些类的成员的方式。例如,len()和的行为可以通过魔术方法和str()覆盖:__len__()__str__()

class EmptySet(object):
    def __len__(self):
        return 0

    def __str__(self):
        return '[]'

>>> e = EmptySet()
>>> str(e)
[]

>>> len(e)
0
Run Code Online (Sandbox Code Playgroud)

还有__cmp__()and__ge__()__le__()方法来控制如何比较这些对象以及如何对它们的列表进行排序list.sort()。我的问题不是关于自定义列表中对象的顺序,而是关于对对象本身进行排序。假设该集合不为空并且我想用sorted()它来排序:

class SetOfTwo(object):
    def __init__(self, a , b):
        el_0 = a
        el_1 = b

    def __len__(self):
        return 2

    def __str__(self):
        return '[{}, {}]'.format(el_0, el_1)
Run Code Online (Sandbox Code Playgroud)

sorted()如果元素不按顺序排列,我可以实现一种神奇的方法来翻转元素吗?我正在想象以下行为:

>>> s = SetOfTwo(2, 1)
>>> str(s)
[2, 1]

>>> t = sorted(s)
>>> str(t)
[1, 2] …
Run Code Online (Sandbox Code Playgroud)

python oop magic-methods

7
推荐指数
1
解决办法
8751
查看次数

我应该直接使用python魔术方法吗?

我从一个人那里听说你不应该直接使用魔法方法。我认为在某些用例中,我必须直接使用魔术方法。这么有经验的开发者,我应该直接使用python魔术方法吗?

python magic-methods

7
推荐指数
1
解决办法
283
查看次数

Python 的迭代器解包(star unpacking)是如何实现的(或者,解包自定义迭代器涉及哪些神奇的方法?)

我正在编写一个定义__iter__and的类__len__,其中 的值__len__取决于__iter__. 我得到了一个有趣的RecursionError.

语言版本:Python 3.8.6、3.7.6。 示例仅用于说明错误。

在以下示例中,Iter.__len__()尝试解包self,将结果存储在 a 中list,然后尝试调用该list.__len__()列表上的内置函数以获取长度。

>>> class Iter:
...     def __iter__(self):
...         return range(5).__iter__()
...     def __len__(self):
...         return list.__len__([*self])
...
>>> len(Iter())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __len__
  File "<stdin>", line 5, in __len__
  File "<stdin>", line 5, in __len__
  [Previous line repeated 993 more times] …
Run Code Online (Sandbox Code Playgroud)

python iterator magic-methods python-3.x iterable-unpacking

7
推荐指数
1
解决办法
199
查看次数