0

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

1
  • For one thing, using var is deprecated. Commented Oct 15, 2009 at 16:17

3 Answers 3

3

I'm pretty concerned by several things I see here

  1. 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.
  2. Usage of global in a class (or even usage of global period) when you should be using aggregation or composition.
  3. 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();
Sign up to request clarification or add additional context in comments.

Comments

1
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;

1 Comment

Were you missing the constructor?
0

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 :(

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.