Álvaro
Álvaro

Reputation: 5

Get Value from function inside Php Class

Hello all people, and thank´s in advance for the help

I try extract value from string inside function and inside class the same time, i put the example, i send my question because few time start with classes and sometimes i have some dudes and don´t get solution for fix the problem, i put my example :

<?php

class example
{
    public $db;

    function __construct($db)
    {
        $this->db = $db;
    }

    function test()
    {
        $value = "okokok";
    }
}

$a = new example("");

$c = $a->test();

echo $c->value;

?>

In my example code i try get the value from string called "$value", i see this until, but sure i writte bad in the code, and by this my question here for see if you can help me for clear my dude and get this value in the best way but outside function or class, thank´s other time by the help

Upvotes: 0

Views: 1094

Answers (1)

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

You have 2 options:

  1. return value from the function:
<?php

class example
{
    public $db;

    function __construct($db)
    {
        $this->db = $db;
    }

    function test()
    {
        return "okokok";
    }
}

$a = new example("");

$c = $a->test();

echo $c;

?>

share PHP code

  1. assign value to class instance property:
<?php

class example
{
    public $db;
    public $value;

    function __construct($db)
    {
        $this->db = $db;
    }

    function test($v)
    {
        $this->value = $v;
    }
}

$a = new example("");

$c = $a->test("new value");

echo $a->value;

?>

share PHP code

Upvotes: 2

Related Questions