开发者

Object Oriented Programming accessing variable values, How to?

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

  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();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜