d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > How To Make This Work In Php
Add Reply New Topic New Poll
Member
Posts: 45,510
Joined: Apr 10 2006
Gold: 53,694.63
Dec 26 2022 08:38am
Code

$d='ddd';

class Cl {
global $d;

public function getData() {
echo $this->d;
}
}



Im trying to access variable $d. It works only if i place global d inside method getdata. How to make it work if i want to place it outside method like above
Member
Posts: 4,689
Joined: May 30 2021
Gold: 4.00
Dec 26 2022 09:01pm
Trying to access an out-of-scope variable that way defeats the purpose of using a class. It’s probably better just to pass the variable as an argument to your public function’s parameter. Or more of an OOP way, you would have a setData() that does the aforementioned functionality and updates a private data member, then getData() merely returns the private data’s value.
Member
Posts: 2,030
Joined: Feb 4 2006
Gold: 0.00
Dec 29 2022 01:50am
Code

<?php

$d='ddd';

class Cl {

private $d;

public function __construct(){
global $d;
$this->d = $d;
}
//option 1
public function getData() {
return $this->d;
}
//option 2
public function getDataV2() {
return $GLOBALS['d'] ?? NULL;
}
}

$c = new Cl();
var_dump($c->getData());
var_dump($c->getDataV2());



Note what r4f said, in general you should not use globals anywhere in your code.
Member
Posts: 45,510
Joined: Apr 10 2006
Gold: 53,694.63
Dec 29 2022 10:10am
i have bypass that with constants

define(xyz,zzz);

now the only global i use is mysqli inside class methods

This post was edited by undead_lord on Dec 29 2022 10:11am
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll