Php class calling object

PHP : Best way to call an object method from another object ?

I am searching for the best way to call a class method from another class, without having to use Global to fetch the class instance, cus as i understand now that «Global is evil» ! Here is some code to explain it more:

class Assets< public $assets = array(); public function add($asset)< $this->assets[] = $asset; > > 
$assets = new Assets; class Form< public function __construct()< global $assets; $assets->add('Form'); > > 

Is using Global in such scenario is THAT bad ? If so, what other way is considered to be the best ? PS: I need to work with only one instance of the class; means that i don’t want to create a new instance inside of the second class.

Dependency injection is the «language-provided & standard» solution. You are just really bad at OOP. Maybe this list helps a bit.

@Dewan159 I think you’re looking at this from the wrong-end in, which is common when one first starts diving deeply into OOP with PHP when coming from a procedural approach and talking about «practice». Do you understand why global is «bad»? Try to focus on that first. Develop your knowledge of the approach before criticizing the language flatly and you will be better received when looking for help. The advantages will be more readily apparent once you’re a little more familiar with why injection is important (it’s used all over the Java world, for example.)

@Dewan159 I wasn’t making a qualitative statement about your question 🙂 I was simply noting that the snippets you provided evince wrong-headed goals in design. What you’re identifying as a weakness is an almost universally accepted coding practice across many languages besides PHP (Python, many JVM langs, Ruby all have some variant of DI available to you.) It’s a backbone of OOP. Your predilection to look at this pattern as problem probably means you have some wrong-headed goals in the code your writing. You mention writing a framework. Perhaps we could continue in chat?

@Dewan159: if you don’t always want people to have to pass the assets object, then simply don’t force them to use the constructor. Provide a factory class that you pass the Assets instance once, and let the factory always construct your form classes.

Читайте также:  Php регулярные выражения поиск символов

6 Answers 6

If you only want to have 1 instance of assets, you need to use some form of dependency injection.

The most obvious in this case, is passing it through the constructor:

It is indeed a bad idea to use globals.

Yea it’s a great practice. There’s a few other ways that are also considered ‘good’, but global , static or singletons are all considered kinda bad in acedemic OOP design. Avoid those while you can.

@Evert , while this is a lot better then ever other «answer», you really should avoid performing any computation in the constructors. It tends to turn testing in a nightmare.

You could also make Assets a singleton if it makes sense in your context:

class Assets < ///////////////////// // Your stuff // ///////////////////// private $assets = array(); public function add($asset) < $this->assets[] = $asset; > ///////////////////// // Singleton stuff // ///////////////////// static private $instance = null; static public function getInstance() < if(self::$instance == null) self::$instance = new self; return self::$instance; >// To restrict construction of this class outside of this class definition private function __construct() <> // To restrict cloning of this class outside of this class definition private function __clone() <> > 

In your other code, you’d use the singleton like this:

I think it always depends on what you’re trying to do. When taking into account that some pretty large projects (like for example the open source 3D engine Ogre3D) use singletons a lot, I would not say that Singletons are generally a bad practice.

Injection is definitly the way to go. Hiding the construction inside of another constructor is bad practice and will only make things harder on yourself in the long run (for example, you find a use case where the same Assets instance should be used from a different instance of Form)

I’m not answering this question directly with the provided elements, I just show a way of sharing data between objects without using globals.

class A < private $v; function __construct ($value) < $this->v = $value; > function set_v ($value) < $this->v = $value; > function print_v () < echo $this->v; > > 
class B < private $a; function __construct (&$tha) < if ($tha) < $this->a = $tha; > > function print_a () < echo $this->a->print_v(); > > 
$mya = new A(12); $mya->print_v(); // echo 12 $myb = new B($mya); $mya->set_v(13); $myb->print_a(); // echo 13 

You can keep a trace of one object in another and respecting the encapsulation of the objects. If an instance of A however get removed, an instance of B could get unreliable. You should then make sure that the data is always reliable within the object storing it (e.g. making a method that verify if the internal data is alright).

Читайте также:  Javascript array methods join

Also as noticed by tereško, arguments explicitly awaiting for a reference should be avoided. In fact since PHP 5.0 a new feature has been introduced to the language called the type hinting. That prevents your program to have undesired memory behavior, plus the fact that any wrong matching can be monitored at the compilation level (more details at Type Hinting (PHP official documentation))

function __construct (A $tha) .. 

Источник

PHP: Calling another class’ method

I’m still learning OOP so this might not even be possible (although I would be surprised if so), I need some help calling another classes method. For example in ClassA I have this method:

now from ClassB (different file, but in the same directory), I want to call ClassA ‘s getName() , how do I do that? I tried to just do an include() but that does not work. Thanks!

Does class B have any relation to class A (such as hierarchical)? If so, Class B can extend class A and you will have access to class A’s functions. If not, can you describe your two objects a little more (what they represent).

The thing is, Class A is already extending another class (simple_html_dom that I downloaded from the net) so I dont want to (dont even know if I can) extend Class A which is already extending some other class

@evert, I dont have any code. I was hoping someone could give me some code to do what I wrote above as I am stuck.

4 Answers 4

//file1.php name; > > ?> //file2.php function callA() < $classA = new ClassA(); $name = $classA->getName(); echo $name; //Prints John > > $classb = new ClassB(); $classb->callA(); ?> 

Note that you cannot easily unit test your B class now, because you have tightly coupled to A class to it.

right — that include should probably be in a controlling file that calls both A and B instead of B including A. In this example you would always be instantiating A when you load B. But it should be easy for you to separate.

That’s another lesson for the OP to learn another day. all the OP needs now is basics. Thanks for pointing that out anyway

If they are separate classes you can do something like the following:

class A < private $name; public function __construct() < $this->name = 'Some Name'; > public function getName() < return $this->name; > > class B < private $a; public function __construct(A $a) < $this->a = $a; > function getNameOfA() < return $this->a->getName(); > > $a = new A(); $b = new B($a); $b->getNameOfA(); 

What I have done in this example is first create a new instance of the A class. And after that I have created a new instance of the B class to which I pass the instance of A into the constructor. Now B can access all the public members of the A class using $this->a .

Читайте также:  Команда закрытия консоли java

Also note that I don’t instantiate the A class inside the B class because that would mean I tighly couple the two classes. This makes it hard to:

Источник

Calling an object of class in another class

I am a newbie to OOP. I have worked in procedural programming a lot. So i am in little trouble right now. Can you please tell me how to call an object of a class in another class and then i can access all the variables and function of that class with using that object. For e.g I have a class of DBconnection. i write my db queries in it. Now i have an other class named Users. Now i need to access the db queries in User class, definitely i need object of DBconnection class to access all db queries. What can i do please help The example code which i have written is as below:

**DBConnection class** class DBConnection < public $SITEURL; public $servername; public $username; public $password; public $dbname; public $objDbConnect; function DBConnection()< $this->SITEURL=Configuration::SITEURL; $this->servername=Configuration::servername; $this->username=Configuration::username; $this->password=Configuration::password; $this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password); if($this->objDbConnect)< mysql_select_db($this->dbname); > > function InsertRecord($pStrTableName,$pArrField,$pArrValue) < $strSql="insert into $pStrTableName ("; $intFieldSize=count($pArrField); for($i=0;$i<$intFieldSize;$i++) < if($i==$intFieldSize-1) < $strSql.=$pArrField[$i]; >else < $strSql.=$pArrField[$i].","; >> $strSql.=") values ("; $intFieldSize=count($pArrValue); for($i=0;$i <$intFieldSize;$i++) < if($i==$intFieldSize-1) < $strSql.="'".$pArrValue[$i]."'"; >else < $strSql.="'".$pArrValue[$i]."'".","; >> $strSql.=")"; if(mysql_query($strSql)) < return 1; >else < return 0; >> > **Users class** class Users < var $username, $userpassword, $email, function User()< >> 

6 Answers 6

The best way to do this would be to use Singleton pattern. Following is an example

class DBConnection < private static $instance = null; private function __construct() < >/* * @return DBConnection */ public static function get_db() < if ( empty(self::$instance) ) self::$instance = new DBConnection(); return self::$instance; >public function query() < >> class User < function testfunc() < $db = DBConnection::get_db(); $db->query(); > > 

You can declare an object of your class in your second class and use it like

$c= new DBConnection(); $c->InsertRecord('Parameters here etc'); echo $c->username; //and other public variables similarly 

i can declare $db = new DBConnection in DBConnection class. so if i include DBConnection class in Users class, it can’t access the functions and variables.

Источник

Оцените статью