0

I'm trying to instantiate a class that use namespace.

<?php namespace CFPropertyList; require_once('CFPropertyList/CFPropertyList.php'); $plist = new CFPropertyList(); ?> 

That's working!

But when I try put that code into my class I get syntax errors. I can't use "namespace CFPropertyList;" in a class?

 <?php class Plist{ public function test(){ namespace CFPropertyList; require_once('CFPropertyList/CFPropertyList.php'); $plist = new CFPropertyList(); } } ?> 

UPDATE:

Thanks to all I got this working.

<?php namespace CFPropertyList; require_once('CFPropertyList/CFPropertyList.php'); class Plist{ public function test(){ //some code } } } 

But is my own class in a namespace now? Sorry for the noob questions. I can't do.

 $plist = new Plist; $plist->test(); 

3 Answers 3

2

Your namespace should be declared before your class, so the class would then belong to that namespace:

plist.php

 <?php namespace CFPropertyList; class Plist{ public function test() { echo 'Test'; } } ?> 

other.php

 <?php require_once('plist.php'); $plist = new CFPropertyList::Plist(); $plist.test(); ?> 
Sign up to request clarification or add additional context in comments.

2 Comments

That's working but, now I got a new problem '$plist = new Plist; $plist->test();'. Class 'Plist' not found
If you are calling it from outside the namespace you need CFPropertyList::Plist
1

You have to put the namespace definition outside the class definition. (Besides that your class definition seems to be pretty messed up. Don't you have any class methods?)

2 Comments

fixed the methods! =) but I can't put the namespace outside the class definition.
That's the only way. See the answer by @air4x.
1

From Defining namespaces

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

So you must declare it at the top of the file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.