How to use a variable from a function in a class - php

I have a function declared in another file. I need to get a variable from it and use it in the class. But for some reason an error appears.
$myvar = myfunc($text);//an error here
class func{
public $title = $myvar;//and here
public function ($title){
...
}
}

You can inject the return value of the function in the constructor when the object is being initialized.
include_once 'func.php';
class Myclass{
public $title;
function __construct( $title = null )
{
$this->title = $title;
}
}
$obj = new Myclass( getVar() );
echo $obj->title;
func.php class
<?php
function getVar()
{
return 'this_var';
}
?>

Your question is about how to use a variable inside a class
class MyClass{
public $title; //do not put a variable here, this is invalid
///you could set a default like this
// e.g. public $title = "Jam";
//this is a setter
public function setTitle(string $title){
$this->title = $title
}
public function getTitle() {
return $this->title;
}
}
then use
$class = new MyClass();
$class->setTitle("jam sponge");
echo $class->getTitle();
or
define a constructor
class MyClass{
public $title;
//this is a constructor
public function __construct(string $title){
$this->title = $title
}
public function getTitle() {
return $this->title;
}
}
then use
$class = new MyClass("jam sponge");
echo $class->getTitle();
the latter is my preference.
As for this $myvar = myfunc($text);//an error here that's not relate to passing the var to the class. You have some other issue in that function, so either show that code or post anew question specific to it

Related

Accessing variables from constructors in static methods

I have a class with methods, some of these methods use the same variable across board - "$company_id". Now, I don't want to explicitly define what is contained in $company_id for every method. I want to define it once in a constructor and then reference it in my methods. Please how do I do this? This is how it looks currently.
public function __construct(){
//what should I do here?
}
public static function getItemLimit(){
$company_id = Auth::user()->company_id;
$item_limit = Company::where('id', $company_id)->count();
return $item_limit;
}
public static function currentItemCount(){
$company_id = Auth::user()->company_id;
$item_count = Item::where('company_id', $company_id)->count();
return $item_count;
}
Try this Use Company_Id instead of $abcVar
class Abc{
public static $abcVar = '';
public function __construct()
{
self::$abcVar = 11;
}
public static function getItemLimit()
{
echo self::$abcVar;
exit;
}
}
$obj = new Abc();
Abc::getItemLimit();

PHP: How do I access a local varibale of a function in class from another function

So i have a php class and i'm having a small snarl up. imagine a class as one shown below
<?php
class Foo
{
public function __construct()
{
$this->bar1();
}
public function bar1()
{
$myvar = 'Booya!';
return 'Something different';
}
public function bar2()
{
//get value of $myvar from bar1()
}
}
$new_foo = new Foo();
$new_foo->bar2();
?>
Question is,
how do I access the variable $myvar from bar1() keeping in mind that bar1() returns something different.
You would do something like this... Everything has been explained through comments next to the code.
<?php
class Foo
{
private $myvar; //<---- Declare the variable !
public function __construct()
{
$this->bar1();
}
public function bar1()
{
$this->myvar = 'Booya!'; //<---- Use this $this keyword
//return 'Something different';//<--- Comment it.. Its not required !
}
public function bar2()
{
return $this->myvar; //<----- You need to add the return keyword
}
}
$new_foo = new Foo();
echo $new_foo->bar2(); //"prints" Booya!
<?php
class Foo
{
var $myvar;
public function __construct()
{
$this->bar1();
}
public function bar1()
{
$this->myvar = 'Booya!';
return 'Something different';
}
public function bar2()
{
//get value of $myvar from bar1()
echo $this->myvar;
}
}
$new_foo = new Foo();
$new_foo->bar2();
?>
You should set it as a class variable first, then access it using $this
You cannot do that directly, only you can do without altering bar1() return value is create a
class variable for saving the value of this data
In class definition add
private $saved_data;
In bar1():
$myvar = 'Booya!';
$this->saved_data = $myvar;
And in bar2()
$myvar_from_bar1 = $this->saved_data
Use class variables like:
$this->myvar = 'Booya!';
Now the variable myvar will be store in the class and can be requested or altered in other methods.

Use a variable from __construct() in other methods

I defined a new variable in __construct() and I want to use it in another function of this class.
But my variable is empty in the other function!
this is my code:
class testObject{
function __construct() {
global $c;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
global $data;
print_r($data);
}
}
Declare variable $data as global inside the constructor:
function __construct() {
global $c;
global $data;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
Then, it will be visible in other function as well.
Note that extensive usage of global variables is strongly discouraged, consider redesigning your class to use class variables with getters+setters.
A more proper way would be to use
class testObject
{
private $data;
function __construct(array $c)
{
$this->data = array(
"name"=>$c['name'],
"family"=>$c['family']
);
}
function showInfo()
{
print_r($this->data);
}
// getter: if you need to access data from outside this class
function getData()
{
return $this->data;
}
}
Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.
class testObject
{
private $name;
private $family;
function __construct($name, $family)
{
$this->name = $name;
$this->family = $family;
}
function showInfo()
{
print("name: " . $this->name . ", family: " . $this->family);
}
// getters
function getName()
{
return $this->name;
}
function getFamily()
{
return $this->family;
}
}
And you can even construct this object with data from you global variable $c until you elimitate it from your code:
new testObject($c['name'], $c['family'])
You can do this way. Instead of declaring $data as global variable declare as public or private or protected variable inside the class depending on your use. Then set the data inside _construct.
Using global inside a class is not a good method. You can use class properties.
class testObject{
public $data;
function __construct() {
global $c;
$this->data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
print_r($this->data);
}
}

Use method of parent class when extending

Probably a silly question.. but how do I correctly use the methods of class Test in class Testb without overriding them?
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
<?php
class Testb extends Test {
public function __construct() {
parent::__construct($name);
}
}
<?php
include('test.php');
include('testb.php');
$a = new Test('John');
$b = new Testb('Batman');
echo $b->getName();
You need to give the Testb constructor a $name parameter too if you want to be able to initialize it with that argument. I modified your Testb class so that its constructor actually takes an argument. The way you currently have it, you should not be able to initialize your Testb class. I use the code as follows:
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Testb extends Test {
// I added the $name parameter to this constructor as well
// before it was blank.
public function __construct($name) {
parent::__construct($name);
}
}
$a = new Test('John');
$b = new Testb('Batman');
echo $a->getName();
echo $b->getName();
?>
Perhaps you do not have error reporting enabled? In any event, you can verify my results here: http://ideone.com/MHP2oX

Php Class - How can I make a Class know parent value

<?php
class FirstClass{
public static $second;
public static $result = 'not this =/';
public function __construct(){
$this->result = 'ok';
$this->second = new SecondClass();
}
public function show(){
echo $this->second->value;
}
}
class SecondClass extends FirstClass{
public $value;
public function __construct(){
$this->value = parent::$result; //Make it get "ok" here
}
}
$temp = new FirstClass();
$temp->show(); //It will show: "not this =/"
?>
How can I make it to print "ok"?
I mean, the SecondClass should know what FirstClass set as result, see?
Replace $this->result = 'ok'; with self::$result = 'ok'; in FirstClass constructor.
Btw, the code is terrible. You're mixing static and instance variables, and extend classes but don't use benefits extension provides.
you need to reference the static as self::$result in the first class.
Below should do what you want...
<?php
class FirstClass{
public static $second;
public static $result = 'not this =/';
public function __construct(){
self::$result = 'ok';
$this->second = new SecondClass();
}
public function show(){
echo $this->second->value;
}
}
class SecondClass extends FirstClass{
public $value;
public function __construct(){
$this->value = parent::$result; //Make it get "ok" here
}
}
$temp = new FirstClass();
$temp->show(); //It will show: "not this =/"
?>

Categories