Hmmm, so how is this done?
I have a class
class Themes extends Access
{
public $theme_name;
public $theme_by;
public $theme_by_email;
public $theme_by_website;
public $theme_description;
public $theme_thumb;
public $theme_source;
public $theme_uploaded_on;
public function __construct()
{
parent::__construct();
//$this->get_theme();
}
public function get_theme()
{
$sql = "SELECT *
FROM `user_themes`
WHERE `user_id` = " . $this->session->get('user_id');
if($this->db->row_count($sql))
{
$result = $this->db->fetch_row_assoc($sql);
$this->$theme_name = $result['theme_name'];
$theme_by = $result['theme_by'];
$theme_by_email = $result['theme_by_email'];
$theme_by_website = $result['theme_by_website'];
$theme_description = $result['theme_description'];
$theme_source = $result['theme_source'];
$theme_uploaded_on = $result['theme_uploaded_on'];
}else{
die('no results');
}
}
}
How can I access these variables and their contents outside of the class?
in my PHP page I have
$theme = new Themes();
I tried to access my variable using
$theme->them_name but I get an undefined error
but don't really know how I can access the variable...
With your current setup, all you have to do is call:
$theme->theme_name;
$theme->theme_by;
etc
However it is generally not good practice to make instance variables public, rather make them private and make mutator methods.
An example would be:
private $theme_name;
public function getThemeName(){
return $this->theme_name;
}
public function setThemeName($theme){
$this->theme_name = $theme;
}
$this->theme_name = $result['theme_name'];
$this->theme_by = $result['theme_by'];
Note on $this prepended.
After that you can access the data using $theme->theme_name etc
Related
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();
I've written a class which in the construct accesses the db and gets a list of names. These names go into an associative array e.g. ('name' => 'id').
i.e. the point is to pass in the name to get back an ID:
$id = names::nameToId('some name');
print $id;
// prints int
The problem is when I try and return the array from the construct I get an error:
Notice: Undefined variable: nameArray in (etc)
Here is the code so far:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while($row = mysqli_fetch_assoc($res)) {
$nameArray[$row['name']] = $row['id'];
}
return $nameArray;
}
static public function nameToId($name) {
$nameId = $nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;
Why doesn't $nameArray get passed to nameToId()? I'm new to classes, and I thought by declaring $nameArray as public when I first create the class that it would make it available. I have also tried to make it global even though I know that is not good form but even still it didn't work.
Because you cannot return anything from a constructor. Any return value is being ignored and just goes into the aether. $nameArray is a local variable and is not shared in any other scope, i.e. you can't access it in nameToId. Further, since nameToId is static, it won't have access to data from any non-static methods like __construct to begin with.
You probably want something like this:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while ($row = mysqli_fetch_assoc($res)) {
$this->nameArray[$row['name']] = $row['id'];
}
}
public function nameToId($name) {
return $this->nameArray[$name];
}
}
$namesToId = new nameToId($mysqli);
echo $namesToId->nameToId('some name');
Fix your code:
class nameToId {
public static $nameArray;
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
$sql = 'SELECT id, name FROM teams';
$res = mysqli_query($this->mysqli,$sql);
while($row = mysqli_fetch_assoc($res)) {
self::$nameArray[$row['name']] = $row['id'];
}
}
static public function nameToId($name) {
$nameId = self::$nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;
I need to use a session information in various functions of my controller, but I can't initialize it in the constructor, because I get an error. Message: Undefined property: Soporte::$session
class Soporte extends MY_Controller {
function __construct(){
parent::__construct( $module, $functionality );
}
public function actualizarSolicitud( $id_solicitud ){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
...
}
public function adminHistorico(){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
$config = array();
...
}
...
}
There's a way to initialize a global variable $user?
Try like below, model is quite complicated so I'm not providing it's code, but you should get the point. Any questions let me know.
/**
* This class is used for performing all read/write session operations
* Native php session is utilized (MY_Session library)
*/
class SessionManager extends BaseLibrary {
private $oUser;
public function __construct() {
parent::__construct();
$this->CI->load->model('User');
}
public function setUser(User $oUser) {
$this->CI->session->set_userdata('userId', $oUser->getId());
}
public function getUser() {
if ($this->oUser === null) {
$this->oUser = new User();
if ($this->CI->session->userdata('userId')) {
$this->oUser->setId($this->CI->session->userdata('userId'));
}
}
return $this->oUser;
}
public function logout() {
$this->CI->session->set_userdata('userId', NULL);
}
}
In the following code, I have to use $module = $this->uri->segment(4);, table = "omc_".$module; and $id = $this->uri->segment(5); in every function in this class.
How can I avoiding this repetition?
Thanks in advance.
class Admin extends Shop_Admin_Controller {
function Admin(){
parent::Shop_Admin_Controller();
}
function changeStatus(){
$module = $this->uri->segment(4);
$table = "omc_".$module;
$id = $this->uri->segment(5);
if($id && $table){
$this->MKaimonokago->changeStatus($table,$id);
}
flashMsg('success',$this->lang->line('kaimonokago_status_changed'));
redirect("$module/admin/index/","refresh");
}
.................
.................
You could simply add then as instance (i.e.: class level) variables with the appropriate visibility (protected or private) and then initialise them within your constructor.
By doing this you wouldn't need to initialise them within each method, and would still have a more convenient naming regime.
For example:
class Admin extends Shop_Admin_Controller {
private $module;
private $table;
private $id;
public function __construct() {
parent::__construct();
// Initialise uri class here, unless this is done
// in the parent constructor.
$this->module = $this->uri->segment(4);
$this->table = "omc_".$module;
$this->id = $this->uri->segment(5);
}
public function changeStatus() {
if($this->id && $this->table) {
...
}
}
}
Incidentally, I'd also recommend setting the appropriate visibility on your methods, unless of course you're targeting PHP 4, in which case replace the "private" with "var" in the above example and remove the visibility properties from the methods.
How about setting them in the constructor?
function Admin(){
parent::Shop_Admin_Controller();
$this->module = $this->uri->segment(4);
$this->table = "omc_" . $this->module;
$this->id = $this->uri->segment(5);
}
They can then be used as e.g. $this->module in the other functions in your class.
This of course presumes that you don't have properties with those names in the parent class. If you do, you use different names.
Maybe set them as protected attributes in your constructor?
class Admin
{
protected $_module;
protected $_table;
protected $_id;
public function __construct()
{
// do something that initializes $this->uri;
$this->_module = $this->uri->segment(4);
$this->_table = 'omc_' . $module;
$this->_id = $this->uri->segment(5);
}
}
I am a learner, I have a class db to help me connect and fetch results in mySQL.
$set = $db->get_row("SELECT * FROM users");
echo $set->name;
this way i use echo results outside a class.
Now i have created another class name user and it has this function
public function name() {
global $db;
$set = $db->get_row("SELECT * FROM users");
$this->name = $set->name;
}
after initializing the class user, when i try to echo $user->name i dont get expected results.
Note i have declared above var $name; in class user
I'm pretty concerned by several things I see here
The method name name() is terribly uncommunicative as to what the method is supposed to do. Remember, methods are actions - try to give them some sort of verb in their name.
Usage of global in a class (or even usage of global period) when you should be using aggregation or composition.
You don't show any execution examples, but I can only assume you never actually call User::name(), which is why your test is failing
Here's some code that addresses these concerns.
<?php
class DB
{
/* Your methods and stuff here */
}
class User
{
protected $db;
protected $name;
public function __construct( DB $db )
{
$this->db = $db;
}
public function getName()
{
if ( is_null( $this->name ) )
{
$set = $this->db->get_row( "SELECT * FROM users" );
$this->name = $set->name;
}
return $this->name;
}
}
$db = new DB();
$user = new User( $db );
echo $user->getName();
class DB
{
public function get_row($q)
{
# do query and store in object
return $object;
}
}
class User
{
public $name;
public function __construct()
{
$this->name();
}
public function name() {
global $db;
$set = $db->get_row("SELECT * FROM users");
echo "<pre>".print_r($set)."</pre>"; # make sure $set is returning what you expected.
$this->name = $set->name;
}
}
$db = new DB();
$user = new User();
echo $user->name;
I am very much sorry, i figured out that problem was on my part, i was using cookies and had two cookies set which were giving problems :(