由于只有狗可以玩"获取",这个例子是好还是坏?由于使用了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轻量级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中,我可以在类的方法中执行此操作:
Condition::evaluate($this, $primaryCondition);
Run Code Online (Sandbox Code Playgroud)
这允许我通过$ this将类的整个实例传递给另一个类.我怎样才能在Ruby中实现同样的目标?