简体   繁体   English

需要 PHP OOP 编码建议

[英]need PHP OOP coding advice

OOP always has lots of classes and their methods. OOP 总是有很多类和它们的方法。 If we need to use several subclass methods or properties that belong to the same class, should we get the high level class first or it's better to use them seperately?如果我们需要使用属于同一个类的多个子类方法或属性,我们应该先获取高级类还是单独使用它们更好? This is an example to show my concern:这是一个例子来表达我的担忧:

Approach I: define variables from the top class seperately方法一:分别定义顶级变量

$var1 = \Drupal::routeMatch()->getRouteName();
......(some process that relies on $var1)

$var2 = \Drupal::routeMatch()->getRawParameters('taxonomy_term');
......(some process that relies on $var2)

Approach II: get the common class first方法二:先拿到普通类

$route = \Drupal::routeMatch();
$var1 = $route->getRouteName();
......(some process that relies on $var1)

$var2 = $route->getRawParameters('taxonomy_term');
......(some process that relies on $var2)

You can assign expressions inline.您可以内联分配表达式。 () causes the return to do 'this first', then return outside of the brackets. ()导致返回执行“先执行此操作”,然后在括号外返回。

$var1 = ($route = \Drupal::routeMatch())->getRouteName();
$var2 = $route->getRawParameters('taxonomy_term');

You can see this as a working demo using some example classes that mimic your environment.您可以将其视为使用一些模拟您环境的示例类的工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM