0

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Álvaro
  • 5
  • 3
  • You're already doing that for `db`... – Álvaro González Feb 16 '21 at 15:14
  • 1) `$value` is a variable available only in [that function's scope](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and). 2) Your `test` method doesn't return a value to be used. – El_Vanja Feb 16 '21 at 15:14
  • 2
    What's your exact question about this? Is there anything not working in your code, besides `value` not being defined? – Nico Haase Feb 16 '21 at 15:16
  • something like [this](https://3v4l.org/TlAIN) - read about the basics [here](https://www.php.net/manual/en/language.oop5.php) – berend Feb 16 '21 at 15:16

1 Answers1

2

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39