Nick
Nick

Reputation: 3384

CakePHP - Call model function from another function within in the same model

I've got a CakePHP model with a few functions in it working well. Now I'm trying to write a new function that uses a few of the functions I've already written. Seems like it should be easy but I can't figure out the syntax. How do I call these functions I've already written within my new one?

Example:

<?php
public function getHostFromURL($url) {
    return parse_url( $http.$url, PHP_URL_HOST );
}
public function getInfoFromURL($url) {
    $host = getHostFromURL($url);
    return $host;
}

Result:

Fatal error: Call to undefined function getHostFromURL() in /var/www/cake/app/Model/Mark.php on line 151

I also tried something like:

<?php
public function getHostFromURL($url) {
    return parse_url( $http.$url, PHP_URL_HOST );
}
public function getInfoFromURL($url) {
    $host = this->Mark->getHostFromURL($url);
    return $host;
}

But got the same result.

Obviously my functions are much more complicated than this (otherwise I'd just reuse them) but this is a good example.

Upvotes: 4

Views: 2951

Answers (2)

Adam Culp
Adam Culp

Reputation: 500

You simply need to call the other function like:

$host = $this->getHostFromURL($url);

Upvotes: 4

dm03514
dm03514

Reputation: 55962

If the function is in the same controller you access functions using

$this->functionName syntax.

You have wrong syntax below:

public function getInfoFromURL($url) {
    $host = this->Mark->getHostFromURL($url);
    return $host;
}

Should be:

public function getInfoFromURL($url) {
        $host = $this->getHostFromURL($url);
        return $host;
    }

If getFromHostUrl method is in the current class. http://php.net/manual/en/language.oop5.php

Upvotes: 5

Related Questions