monkey patching in php

前端 未结 5 1865
悲&欢浪女
悲&欢浪女 2021-01-05 03:49

I\'m trying to figure out how monkey patching works and how I can make it work on my own objects/methods.

I\'ve been looking at this lib, it does exactly what I want

5条回答
  •  时光说笑
    2021-01-05 04:09

    In the case of http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html what actually makes the difference is the \ character used in front of the second strlen.

    When you are using namespaces you can either use a namespace and directly invoke the methods/classes declared in the namespace:

    use TheNamespace;
    $var = new TheClass();
    

    Or invoke the class explicitly by using something like:

    $var = new \TheNamespace\TheClass();

    So by invoking \strlen() instead of strlen() you are explicitly requesting PHP to use the default strlen and not the strlen defined for this namespace.

    As for monkey patching you could use runkit (http://ca.php.net/runkit). Also with regards to patchwork there are a fair amount of examples in their website (http://antecedent.github.com/patchwork/docs/examples.html). You could check the magic method example that is replacing a function in a class.

提交回复
热议问题