小编Dan*_*Dan的帖子

一般多态性与PHP的例子

由于只有狗可以玩"获取",这个例子是好还是坏?由于使用了instanceof,我怀疑这是一个非常糟糕的主意,但我不完全确定原因.

class Animal {
    var $name;
    function __construct($name) {
        $this->name = $name;
    }
}

class Dog extends Animal {
    function speak() {
        return "Woof, woof!";
    }

    function playFetch() {
        return 'getting the stick';
    }
}

class Cat extends Animal {
    function speak() {
        return "Meow...";
    }
}

$animals = array(new Dog('Skip'), new Cat('Snowball'));

foreach($animals as $animal) {
    print $animal->name . " says: " . $animal->speak() . '<br>';
    if ($animal instanceof Dog) echo $animal->playFetch();
}
Run Code Online (Sandbox Code Playgroud)

另一个例子.由于我不断创建具有ID的数据对象,我想我也可以从基类扩展它们以避免代码重复.再次,这是不对的?由于椅子没有名字,狗没有轮子.但它们都是数据对象,因此非常令人困惑.

class Data_Object { …
Run Code Online (Sandbox Code Playgroud)

php polymorphism

28
推荐指数
2
解决办法
5万
查看次数

在我的PHP MVC框架中进行路由

几年来,我一直致力于自己的PHP轻量级MVC框架.我可能会在某个时候根据开源许可证发布.

以下是我用于处理路线的内容:

function routes($routes, $uriPath) {

    // Loop through every route and compare it with the URI
    foreach ($routes as $route => $actualPage) {

        // Create a route with all identifiers replaced with ([^/]+) regex syntax
        // E.g. $route_regex = shop-please/([^/]+)/moo (originally shop-please/:some_identifier/moo)
        $route_regex = preg_replace('@:[^/]+@', '([^/]+)', $route);

        // Check if URI path matches regex pattern, if so create an array of values from the URI
        if(!preg_match('@' . $route_regex . '@', $uriPath, $matches)) continue;

        // Create an array of identifiers …
Run Code Online (Sandbox Code Playgroud)

php regex model-view-controller routes

3
推荐指数
1
解决办法
3867
查看次数

Ruby传递对象实例作为参数

在PHP中,我可以在类的方法中执行此操作:

Condition::evaluate($this, $primaryCondition);
Run Code Online (Sandbox Code Playgroud)

这允许我通过$ this将类的整个实例传递给另一个类.我怎样才能在Ruby中实现同样的目标?

php ruby

2
推荐指数
1
解决办法
5848
查看次数

标签 统计

php ×3

model-view-controller ×1

polymorphism ×1

regex ×1

routes ×1

ruby ×1