alex3410
alex3410

Reputation: 71

Access object instances created by functions in PHP

I am just getting into OOP PHP but have got a little stuck.

Basically i want to create a function to create the objects, the issue is i can't then access the objects outside of the function:

$website0 = new website(0,'test','NameTest');
echo $website0 ->getProperty('name');

This works. However:

createWebsitesFromDatabase();
echo $website0 ->getProperty('name');

function createWebsitesFromDatabase() {
    $website0 = new website (0,'test','NameTest');
}

does not work. Any ideas?

Upvotes: 1

Views: 69

Answers (3)

Stefan Neubert
Stefan Neubert

Reputation: 1054

You have to assign the created object to a variable outside the function by using a return value, that's better than using global in most cases.

<?php
   function createWebsitesFromDatabase(){
       $insideVar = new website(0, 'test', 'NameTest');
       return $insideVar;
   }

   $website0 = createWebsitesFromDatabase();
   echo $website0->getProperty('name');
?>

Upvotes: 2

Nicolas Brown
Nicolas Brown

Reputation: 1574

do this:

function createWebsitesFromDatabase() {
global $website0;
$website0 = new website (0,'test','NameTest');
}

this link should clarify your problem

http://php.net/manual/en/language.variables.scope.php

Upvotes: 0

Peter
Peter

Reputation: 16933

function createWebsitesFromDatabase() {
   global $website0; // here is the trick
   $website0 = new website (0,'test','NameTest');
}

createWebsitesFromDatabase();    
echo $website0 ->getProperty('name');

Upvotes: 1

Related Questions