...

View Full Version : Calling a class then echo'ing it in a function



Apothem
07-18-2008, 04:18 AM
This is just what I know and are trying to explain:
So I have another file called "class.php". It has a class called 'stuff' with the var $hat which has the value '1234';

functions.php calls the class.php and has a function which includes a file called "settings.php" In settings.php, I do this:


$dstuff = new stuff();
function default() {
global $dstuff;
echo $dstuff->hat;
}
default();
It doesn't echo anything. What's wrong?

Edit I solved it; it seems that I need to make $dstuff global in the first function so that the sub function can carry the variable.

Fou-Lu
07-18-2008, 05:06 AM
Thats right, if you have a class thats declared in a function you need to either return its value or use a referencing / global techinque.
BTW, this is PHP4 style objects, you should consider upgrading to PHP5 objects. Leaving properties weaker than protected is not really recommended in any oop language.

Apothem
07-18-2008, 05:37 AM
PHP4 style objects? Can you explain more on the difference?

An extra question: How do you 'control' if statements?

Here's what I mean:

if( is_in_group('Author') || false == $maintenance ) { <--- Start 1
if( widgets_enabled() ) { <--- Start 2
echo "hi";
} <-- End 1
echo "hi again";
} <-- End 2

Since when I tried to do : endif; for them separately, I received an error.When they're both braces, it acts as if the widgets_enabled() should only display "hi".

Also, is there a way to combine objects?

Fou-Lu
07-18-2008, 09:50 PM
PHP5 uses a strong object core supporting scopes, abstracts, static methods and static method calls, and polymorphism implemented late binding. These allow strong control over you're objects:


class MyPHP4Class
{
var $number;
function MyPHP4Class($num)
{
$this->number = $num;
}
function doubleNum()
{
$this->number *= 2;
}
function squareNum($num)
{
return $num * $num;
}
}
$obj = new MyPHP4Class(1); // number = 1
$obj->number = 2; // number = 2
$obj->doubleNum(); // number = 4
$sq = $obj->squareNum(5); // number = 4; sq = 25
$sq = MyPHP4Class::squareNum(5); // number = null; sq = 25

Each member and method can be accessed directly and any method not containing $this can be called statically. PHP5 version forces you to control you're object structures:


class MyPHP5Class
{
private $number;
public function __construct($number)
{
$this->number = $number;
}
function doubleNum() // Default scope in PHP is public
{
$this->number *= 2;
}
public static function squareNum($num)
{
return $num * $num;
}
}
$obj = new MyPHP5Class(1); // Number is 1
$obj->number = 2; // Triggers warning, Number is 1
$obj->doubleNum(); // Number is 2
$sq = $obj->squareNum(5); // Triggers warning, returns void
$sq = MyPHP5Class::squareNum(5); // Number is null, sq is 25

A lot more control exists in the PHP5, plus you can extend parent classes, implement interfaces and create late static and object binding. PHP5's object core is quite good given its a procedural language.

As for you're if, don't bother using endif; style syntax - its nice but it does represent too much psuedocode for my liking. Standard braces are easiest to follow:


if( is_in_group('Author') || false == $maintenance )
{
if( widgets_enabled() )
{
echo "hi";
}
echo "hi again";
}

I don't quite see what you mean about the problem with it. If you are in_group('Author') or $maintenance is false you enter the first condition and if widgets_enabled is not false you output hi followed by hi again, otherwise just hi again. Though I don't use the pseudo style syntax, I believe you can nest with the alternative syntax and write it like so:


if( is_in_group('Author') || false == $maintenance ):
if( widgets_enabled()):
echo "hi";
endif;
echo "hi again";
endif;


And finally, objects cannot be combined. Instead, you can create child objects which extend parent objects. Any properties or methods with a protected or public scope can be accessed by the child class, and the child class can write extended functionality for the original object. This is the closest you can come to combining classes together.

Apothem
07-18-2008, 11:33 PM
Oh, so that's what static does; I was always confused on that. So it pretty much allows you to call a class through:
class::FUNCTION right? And that function must not use $this? Though, I don't really see a lot of use of classes with functions that doesn't have $this in it; it can be used as a normal function then, right?

Also, public... is that required by default or no?
And also, what's the difference between private and protect?

Fou-Lu
07-19-2008, 01:16 AM
Public - Available access anywhere. It is the default scope in PHP.
Private - Only this class can access the method/property
Protected - Only this class and inheriting classes can access the method/property

A static method is essentially just a function, but one that logically fits with the class. Say you have a class that represents a user, with username and userid. A static method would be something like fetch all users in a database and return them as an array of users:


class User
{
private $userid;
private $username;
public function __construct($userid = 0, $username = '')
{
$this->userid = $userid;
$this->username = $username;
}
// Class methods here
public static function getUsers()
{
$aResult = array();
$sQry = "SELECT userid, username FROM users";
$qry = mysql_query($sQry) or die(mysql_error());
while ($record = mysql_fetch_assoc($qry))
{
$aResult[] = new User((int)$record['userid'], $record['username']);
}

return $aResult;
}
}

for example. You get used to handling objects the more you use them.

Apothem
07-19-2008, 07:22 AM
Might I ask... why is there a __construct? Is that the thing which is for the class properties when called?

Fou-Lu
07-19-2008, 07:46 AM
__construct is PHP5's upgrade from the classname constructor. It used to be that you used a function declared the same as the class:


class MyClass
{
public function MyClass()...
}

I have no idea why they chose to change it to construct, but the old method still works. The benefit of __construct is that you can change you're class name and it still works without having to change the method name.

Construct is automatically called when you construct the object - hense its name and its type (constructor). This is executed when you call new ObjectName(). The example in my last post would be constructed with $obj = new User(0, 'Fou-Lu'); for example which would create a new user with the userid of 0 and the username of Fou-Lu.
Constructors can also have a scope, which is handy in something called a 'Singleton' pattern, or an object that can only have one instance (such as a database for example). This would be done like so:


class MySingleton
{
private static $aInstances = array();
protected final function __construct(){}
public static function createInstance()
{
$className = func_get_arg(0);
// You can either reject or just return. We'll reject:
if (empty($className) || isset(self::$aInstances[$className]))
{
throw new Exception('You cannot instantiate more than one ' . $className . '!');
}
return new $className();
}
}

class MyClass extends Singleton
{
// No constructor as the singleton has a final call
public static function createInstance()
{
return parent::createInstance(get_class());
}
}

Singleton is a great use for forcing a factory type pattern as well. This is a more advanced OOP technique. The above will allow you to create you're object with a call $obj = MyClass::createInstance(); but will forbid you from calling $obj = new MyClass();.

The PHP manual is great for PHP specific syntax on object, but doesn't really explain the concepts of OOP. I would probably recommend a search for 'object oriented concepts' and you will likely get a whole ton of great tutorials. Stick with java or C# if you can't find any PHP, they are not the same but you should get a feel for what the language comparisons are - don't go with C++, it will drive you insane in comparison to java >.<

Apothem
07-19-2008, 04:25 PM
Ah, I see. What's final for, now?

I'll look up object oriented concepts right now.

Fou-Lu
07-19-2008, 06:52 PM
Final declares a non-overridable method. It is useless on a private scope. In our case __construct, any inheriting child does not have the ability to redefine how the construct works preventing users from instantiating multiple instances of the class. The only way that can construct their object is to call the createInstance method allowing them only one instance of the object.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum