简体   繁体   English

CakePHP2.0如何在组件内使用函数?

[英]CakePHP2.0 How to use a function within a component?

This might be a very noob question, but I can't seem to find the answer anywhere. 这可能是一个非常菜鸟般的问题,但我似乎无法在任何地方找到答案。 Is it possible to make your own function in a component and call it in the same component? 是否可以在组件中创建自己的函数并在同一组件中调用它?

Example: 例:

Class myComponent extends Component{

 public function doSomething(){

  doThis();

  $b = $a + 2;

  return $b;

 }

 function doThis(){

  $a = 0;

 }

}

You are mixing up several things here. 您在这里混淆了几件事。

  1. You can generally create object methods like this without problem. 通常,您可以毫无问题地创建这样的对象方法 You have to call them as objects methods though: 但是,您必须将它们称为对象方法:

     public function doSomething() { $this->doThis(); ... } 
  2. Just calling doThis() won't magically create the variable $a in the calling scope. 仅调用doThis()不会在调用范围内神奇地创建变量$a The variable will be created inside doThis and will be contained there. 该变量将在doThis内部创建并将包含在其中。 And that's a good thing. 那是一件好事。 You'll have to explicitly return the value from the method to make it available: 您必须从方法中显式return值以使其可用:

     public function doSomething() { $a = $this->doThis(); ... } protected function doThis() { return 0; } 

Variable scope would mean that the $a inside the doThis function is lost when the function finishes, but you could do this: 可变范围将意味着doThis函数中的$a在函数完成时会丢失,但是您可以这样做:

Class myComponent extends Component
{
    public function doSomething()
    {
        $a=$this->doThis();
        $b = $a + 2;
        return $b;
    }

    function doThis()
    {
        $a = 0;
        return $a;
    }

}

I would probably use a class property like this though: 我可能会使用这样的类属性:

Class myComponent extends Component
{
    public $a;
    public function doSomething()
    {
        $this->doThis();
        $b = $this_.a + 2;
        return $b;
    }

    public function doThis()
    {
        $this->a = 0;
    }

}

Class properties are a great way to update information through a function. 类属性是通过函数更新信息的好方法。 They are accessible to the entire class anywhere. 整个班级的任何地方都可以访问它们。 If you declare it via public if can be used outside the class directly via the instance like this: 如果您通过public声明它,那么可以直接通过此类实例在类外部使用它:

$var=new myComponent();
// Crete a new instance of the object.
echo $var->a; // Outputs the value.

Alternately you can use private properties which are visible to the object itself within the functions, but invisible to the outside world (well, not accessible anyhow). 或者,您可以使用private属性,这些private属性对函数内部的对象本身是可见的,但对于外部世界是不可见的(嗯,无论如何都无法访问)。

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

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