开发者

php namespaces on the fly

开发者 https://www.devze.com 2023-02-01 12:04 出处:网络
I asked a question yesterday about namespaces that got answered, and so I tarried along. The further I get into this thing though, the more I realize, I would really like to be able to generate namesp

I asked a question yesterday about namespaces that got answered, and so I tarried along. The further I get into this thing though, the more I realize, I would really like to be able to generate namespaces on the fly. Reason being, I have a plugins directory where all the files get included. If someone from my company is making a plugin....or a third-party, I don't want them 开发者_JAVA百科to have to bother with the namespaces. I would like to just generate the namespaces on the fly by directory structure. You say, "why not just do that!" Well, I did, but I realize I still have the potential problem of classes being named the same thing and namespaces would solve this problem. Packages would solve this problem also, but I can't find that php supports them.

-plugin
    -tabs
      +tabs.php
    -package
        -tabs
            +tabs.php

The idea is to be able to access the classes by $tabs->func() and $package_tabs->func();

Again, that is not problem, except for the darn possibility of classes being named the same thing.

I have a workaround, but if anyone know of a workaround for dynamically creating namespaces on the fly, it would interesting to hear.

The one problem I see is that PHP creates the namespace at "compile" time. So using something like fsocks to pass in a namespace was a failed attempt.


It's not possible to do dynamically. As you mention, PHP expands the framework at compile time, so nothing in PHP itself can modify that.

Now, you could build a program to "install" these scripts by traversing the directory structure and checking for namespaces. And if it doesn't find one, automatically edit the file and add the namespace definition at the top. But beware that this will be problematic since any classes that are used will likely not be fully qualified (and hence throw errors at compile time).

So the best way would just be to develop the classes with the namespaces from the beginning. It's not that hard to do, and could be documented easily...

0

精彩评论

暂无评论...
验证码 换一张
取 消