hope_industries
hope_industries

Reputation: 473

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;

 }

}

Upvotes: 0

Views: 158

Answers (2)

Fluffeh
Fluffeh

Reputation: 33504

Variable scope would mean that the $a inside the doThis function is lost when the function finishes, but you could do this:

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:

$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).

Upvotes: 0

deceze
deceze

Reputation: 521994

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. The variable will be created inside doThis and will be contained there. And that's a good thing. You'll have to explicitly return the value from the method to make it available:

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

Upvotes: 4

Related Questions