如何 return 并打印特定方法?

How to return and print a specific method?

我在 class 中有 2 个方法。

第一种方法 get $id 通过网络服务检索特定项目的 3 个参数。它是房地产系统的网络服务。我将使用这 3 个参数来查找相关项目。

到目前为止,一切正常。

我的问题是 return resemblant() 方法的数据。

我实例化 object,我将 $id 发送到 features 方法,我注册了 attributes .

$get属性return信息但是$similar = $obj->resemblant()没有return。

我在学习。

How to return the data that is inside the method resemblant() in $similar?

<?php 

require("Acesso.class.php");

class Semelhantes extends Acesso
{
    public function features($id)
    {
        $postFields  = '{"fields":["Codigo","Categoria","Bairro","Cidade","ValorVenda","ValorLocacao","Dormitorios","Suites","Vagas","AreaTotal","AreaPrivativa","Caracteristicas","InfraEstrutura"]}';
        $url         = 'http://danielbo-rest.vistahost.com.br/'.$this->vsimoveis.'/'.$this->vsdetalhes.'?key=' . $this->vskey;
        $url           .= '&imovel='.$id.'&pesquisa=' . $postFields;

        $ch = curl_init($url);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER , array( 'Accept: application/json' ) );
        $result = curl_exec($ch); 
        $result = json_decode($result, true);

        /**
         * Paramentros para filtrar semelhança
         * @var [type]
         */
        $fcidade    = str_replace(" ", "+", $result['Cidade']);
        $fdorms     = $result['Dormitorios'];
        $fvalor     = $result['ValorVenda'];

        return array(
            'cidade' => $fcidade, 
            'dorms' => $fdorms, 
            'valor' => $fvalor
        );

    }

    public function resemblant()
    {
        $get = $this->features($id);
        return $get['Cidade'];
    }

}

/* Chamando as funções em outra parte do sistema */
$obj        = new Semelhantes;
$features   = $obj->features(2);
$similar    = $obj->resemblant();

非常感谢

在第一个函数中,您像这样设置数组:

return array(
   'cidade' => $fcidade, 
   'dorms'  => $fdorms, 
   'valor'  => $fvalor
);

在第二个函数中,您可以像这样访问值:

return $get['Cidade'];

注意到 cidadeCidade 了吗?不同情况。这就是你想要做的:

return $get['cidade'];

您可以在此处阅读有关数组区分大小写的更多信息:PHP array, Are array indexes case sensitive?

您有多种选择可以解决此处的问题

首先可以改resemblant()接收一个参数

public function resemblant($id)
{
    $get = $this->features($id);
    return $get['cidade'];   // case of variable fixed also
}

并使用与 features()

相同的参数调用它
/* Chamando as funções em outra parte do sistema */
$obj        = new Semelhantes;
$features   = $obj->features(2);
$similar    = $obj->resemblant(2);
echo $similar;

或者您可以将传递给 features() 的参数保存为 属性 并在 resemblant()

中重复使用
protected $last_id;

public function features($id)
{

    $this->last_id = $id;

    // other existing code

}

public function resemblant()
{
    $get = $this->features($this->last_id);
    return $get['cidade'];   // case of variable fixed also
}

然后像原来那样调用这些方法

/* Chamando as funções em outra parte do sistema */
$obj        = new Semelhantes;
$features   = $obj->features(2);
$similar    = $obj->resemblant();

echo $similar;